在mvc 4中使用HTML帮助程序选择下拉列表

时间:2014-11-16 09:16:43

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我需要在html帮助器中选择下拉列表。我使用ViewData在IEnumerable中传递我的数据,请帮助我如何用值选择它。

我的代码是

@Html.DropDownList("Brand", ViewData["Brand"] as IEnumerable<SelectListItem>, item.BrandMaster, new { @class = "form-control Repeat TableMust"})

这里

  1. ViewData["Brand"]是我的下拉列表。
  2. 我想在下拉列表中选择item.BrandMaster值。
  3. 但问题是它显示的是文本,但它不包含值。值为“”为空,如何在html助手中选择它?

3 个答案:

答案 0 :(得分:1)

如果你的ViewData["Brand"]包含一个对象IEnumerable<SelectListItem>,我想你已经使用过它的构造函数或更可能的对象初始化程序,例如:

List<SelectListItem> brand = new List<SelectListItem>()
{
   new { Value = 1 , Text = "something 1"  },
   new { Value = 2 , Text = "something 2"  },
   new { Value = 3 , Text = "something 3"  },
};
ViewData["Brand"] = brand;

在您的视图中,您将列表用作DropDownList助手的第二个参数。您还需要提供其值和文本。最后一个参数表示默认选择哪个值:

@Html.DopDownList("Brand",
    (List<SelectListItem>)ViewData["Brand"],
    "value", "text", 2)

你也可以尝试SelectList容器来填充&#34; DropDownList助手。只需发送您的对象列表以在ViewData等中查看,并将其用作第二个参数。然后分别提供Value和Text作为第三个和第四个参数。最后一个参数对应于列表中所选项目的值。

@Html.DropDownList("Brand", new SelectList(
    Model.ListOfYourObjects,
    "<<< Property name as value in the Object, e.g. ID",
    "<<< Property name as text in the Object, e.g. Name/Title/etc.",
    <<< value of thecurrent ID >>>));

e.g。

public class City
{
    public int ID { get; set; }
    public string Name { get; set; }
}

然后

ViewData["Cities"] = dbContext.Cities.ToList();
//or
ViewData["Cities"] = new List<City>(); // fill this list

在视图中:

@model List<City>
// ...
@Html.DropDownList(
    "Brand",
    new SelectList(
        Model, "ID", "Name",
        <<< value of ID to be selected or null>>>
    )
);

IDName是类City中的属性名称,这对于SelectList来说非常重要。

我无法尝试此代码,但这应该可以为您提供一些帮助。希望它可以提供帮助。

答案 1 :(得分:0)

如果您绑定的属性名为BrandMaster,那么它应该是

@Html.DropDownListFor(m => m.BrandMaster, ViewData["Brand"] as IEnumerable<SelectListItem>, 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<SelectListItem>, new { @class = "form-control Repeat TableMust"})
@Html.TextBoxFor(m => m.AnotherProperty)

主视图

@model IEnumerable<MyModel>
@using (Html.BeginForm())
{
  @Html.EditorFor(m => m, new { Brand = ViewData["Brand"])
  ....
}

答案 2 :(得分:0)

在构建下拉列表时,您可以使用SelectListItem的Selected属性选择所选项目

myModelCollection = SomeService.GetModels();
var dropdown = myModelCollection.Select(s => new SelectListItem {Value = s.Id, Name = s.Name, Selected = s.Id == YourSelectedValue} ).ToList();