我是MVC 4的新手,我想创建一个用于列出性别的下拉菜单。我尝试了很多,但没有任何帮助我,我也谷歌它但是invain.Please帮助我在它创建下拉菜单为性别请指导我。
答案 0 :(得分:5)
说我们使用enum作为性别:
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帮助器使用以下两个参数:
List<SelectListItem>()
。答案 1 :(得分:5)
<div class="editor-field">
@Html.DropDownList("Gender", new List<SelectListItem>{
new SelectListItem{ Text="Male", Value="Male"},
new SelectListItem{ Text="Female", Value="Female"}
}, "--- Select ---"
)
</div>
答案 2 :(得分:0)
为性别创建一个类
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" })