在mvc 4中使用HTML帮助程序选择下拉列表
我需要在html帮助器中选择下拉列表。 我使用ViewData在IEnumerable中传递我的数据,请帮助我如何用值选择它。
我的代码是
@Html.DropDownList("Brand", ViewData["Brand"] as IEnumerable, item.BrandMaster, new { @class = "form-control Repeat TableMust"})
这里
-
ViewData["Brand"]
是我的下拉列表。 - 我想在下拉列表中选择
item.BrandMaster
值。
但问题是它显示的是文本,但它不包含值。 值为“”为空,如何在html助手中选择它?
如果你的ViewData["Brand"]
包含一个IEnumerable
对象,我猜你已经使用过它的构造函数或更可能的Object Initializer,例如:
List brand = new List () { new { Value = 1 , Text = "something 1" }, new { Value = 2 , Text = "something 2" }, new { Value = 3 , Text = "something 3" }, }; ViewData["Brand"] = brand;
在View中,您使用列表作为DropDownList
帮助程序的第二个参数。 您还需要提供其值和文本。 最后一个参数表示默认选择哪个值:
@Html.DopDownList("Brand", (List)ViewData["Brand"], "value", "text", 2)
您还可以尝试使用SelectList
容器来“填充” DropDownList
帮助程序。 只需发送您的对象列表以在ViewData等中查看,并将其用作第二个参数。 然后分别提供Value和Text作为第三个和第四个参数。 最后一个参数对应于列表中所选项目的值。
@Html.DropDownList("Brand", new SelectList( Model.ListOfYourObjects, "<<< Property name as value in the Object, eg ID", "<<< Property name as text in the Object, eg Name/Title/etc.", <<< value of thecurrent ID >>>));
例如
public class City { public int ID { get; set; } public string Name { get; set; } }
然后
ViewData["Cities"] = dbContext.Cities.ToList(); //or ViewData["Cities"] = new List(); // fill this list
在一个视图中:
@model List // ... @Html.DropDownList( "Brand", new SelectList( Model, "ID", "Name", <<< value of ID to be selected or null>>> ) );
ID
和Name
是City
类中的属性名称,这对于SelectList
的工作很重要。
我无法尝试此代码,但这应该给你一些工作。 希望它可以提供帮助。
如果您绑定的属性名为BrandMaster
那么它应该是
@Html.DropDownListFor(m => m.BrandMaster, ViewData["Brand"] as IEnumerable, new { @class = "form-control Repeat TableMust"})
如果BrandMaster
的值与其中一个SelectList项的值匹配,则默认情况下将选中它。
始终使用强类型助手!
编辑
要使用为集合的属性创建下拉列表,您需要为模型使用自定义EditorTemplate
public class MyModel { public int BrandMaster { get; set; } public string AnotherProperty { get; set; } }
MyModel.cshtml(在Views/Shared/EditorTemplates
@model MyModel @Html.DropDownListFor(m => m.BrandMaster, ViewData["Brand"] as IEnumerable, new { @class = "form-control Repeat TableMust"}) @Html.TextBoxFor(m => m.AnotherProperty)
主视图
@model IEnumerable @using (Html.BeginForm()) { @Html.EditorFor(m => m, new { Brand = ViewData["Brand"]) .... }
在构建下拉列表时,可以使用SelectListItem的Selected
属性选择所选项
myModelCollection = SomeService.GetModels(); var dropdown = myModelCollection.Select(s => new SelectListItem {Value = s.Id, Name = s.Name, Selected = s.Id == YourSelectedValue} ).ToList();