【发布时间】:2015-08-03 21:44:41
【问题描述】:
我是 MVC 4 的新手,我想创建一个下拉菜单来列出性别。我尝试了很多,但没有任何帮助,我也用谷歌搜索但无济于事。请帮助我创建下拉菜单性别请指导我。
【问题讨论】:
标签: asp.net-mvc-4 drop-down-menu
我是 MVC 4 的新手,我想创建一个下拉菜单来列出性别。我尝试了很多,但没有任何帮助,我也用谷歌搜索但无济于事。请帮助我创建下拉菜单性别请指导我。
【问题讨论】:
标签: asp.net-mvc-4 drop-down-menu
<div class="editor-field">
@Html.DropDownList("Gender", new List<SelectListItem>{
new SelectListItem{ Text="Male", Value="Male"},
new SelectListItem{ Text="Female", Value="Female"}
}, "--- Select ---"
)
</div>
【讨论】:
假设我们使用枚举来表示性别:
namespace DropdownExample.Models
{
public enum GenderType
{
Male=1,
Female=2
}
}
我们制作一个这样的模型:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace DropdownExample.Models
{
public class ActionModel
{
public ActionModel()
{
ActionsList = new List<SelectListItem>();
}
[Display(Name="Gender")]
public int ActionId { get; set; }
public IEnumerable<SelectListItem> ActionsList { get; set; }
}
}
像这样制作一个控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using DropdownExample.Models;
namespace DropdownExample.Controllers
{
public class ActionController : Controller
{
public ActionResult Index()
{
ActionModel model = new ActionModel();
IEnumerable<GenderType> GenderType = Enum.GetValues(typeof(GenderType))
.Cast<GenderType>();
model.ActionsList = from action in actionTypes
select new SelectListItem
{
Text = action.ToString(),
Value = ((int)action).ToString()
};
return View(model);
}
}
}
然后在您看来,您使用 DropDownListFor html 帮助器包括以下内容:
@model DropdownExample.Models.ActionModel
@{
ViewBag.Title = "Index";
}
@Html.LabelFor(model=>model.ActionId)
@Html.DropDownListFor(model=>model.ActionId, Model.ActionsList)
DropDownListFor html 助手使用 at leats 这两个参数:
List<SelectListItem>() 包含下拉列表中的所有选项。【讨论】:
为性别创建一个类
public class Gender
{
public int ID { get; set;}
public string Name { get; set; }
}
在 Controller 中的任意位置创建 Gender 列表
List<Gender> genderList = new List<Gender> {
new Gender{ Name="Male", ID = 1},
new Gender{ Name="Female", ID = 2}
};
您必须在将传递给视图的 Action 中为性别创建一个 SelectList。
ViewBag.Genders= new SelectList(genderList,"ID","Name");
最后,您将向视图添加一个 DropDownList
@Html.DropDownList("Genders", null, htmlAttributes: new { @id = "genders", @class = "form-control" })
@Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
【讨论】: