I am new to MVC 4, i want to create a drop downmenu for listing the gender.I tried a lot but nothing helped me, also i google it but invain.Please help me in it tha thow to create dropdown menu for gender please guide me.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
say we use an enum for the gender:
namespace DropdownExample.Models
{
public enum GenderType
{
Male=1,
Female=2
}
}
and we make a model like this:
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; }
}
}
make a controller like so:
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);
}
}
}
then in your view, you use the DropDownListFor html helper you include the following:
@model DropdownExample.Models.ActionModel
@{
ViewBag.Title = "Index";
}
@Html.LabelFor(model=>model.ActionId)
@Html.DropDownListFor(model=>model.ActionId, Model.ActionsList)
the DropDownListFor html helper uses at leats these two parameters:
- the name of the property that will hold the selected value
- the
List<SelectListItem>()
that contains all the options in the dropdownlist.
回答2:
<div class="editor-field">
@Html.DropDownList("Gender", new List<SelectListItem>{
new SelectListItem{ Text="Male", Value="Male"},
new SelectListItem{ Text="Female", Value="Female"}
}, "--- Select ---"
)
</div>
回答3:
Create a Class for Gender
public class Gender
{
public int ID { get; set;}
public string Name { get; set; }
}
Create a list for Gender anywhere in the Controller
List<Gender> genderList = new List<Gender> {
new Gender{ Name="Male", ID = 1},
new Gender{ Name="Female", ID = 2}
};
You will have to create a SelectList for genders in the Action that will be passed to the view.
ViewBag.Genders= new SelectList(genderList,"ID","Name");
Finally you'll add a DropDownList to the view
@Html.DropDownList("Genders", null, htmlAttributes: new { @id = "genders", @class = "form-control" })
@Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })