视图设置中的MVC下拉列表选择了值

时间:2012-10-09 00:22:43

标签: asp.net-mvc drop-down-menu

我试图为下拉列表设置所选的值。

在控制器中我有

ViewData["productType"] = new SelectList(myDropDownList);

在视图中:

<%= Html.DropDownList("productType", ViewData["productType"] as SelectList, "defaultValue")%>

到目前为止很好,但问题是现在我有&#34; defaultValue&#34;在我的下拉列表中两次。所以我在下拉列表中包含了所有值,包括&#34; defaultValue&#34;。但是这段代码会添加&#34; defaultValue&#34;作为第一要素。我看到了两个样本。

我喜欢将选定的valiue设置为&#34; defaultValue&#34;没有添加两次。

我试过

ViewData["productType"] = new SelectList(myDropDownList, "defaultValue" );

但它没有用。

任何人都可以告诉我该怎么做?

1 个答案:

答案 0 :(得分:5)

您不应该使用与下拉列表的第一个参数相同的名称作为第二个参数。在您的示例中,您使用productType来存储所选值和可用值列表。要在ASP.NET MVC中呈现DropDown,您需要2个属性:

<%= Html.DropDownList(
    "selectedProductType", 
    ViewData["productType"] as SelectList, 
    "defaultValue"
) %>

在控制器操作中,您可以设置这两个属性:

ViewData["selectedProductType"] = "abc";
ViewData["productType"] = new SelectList(myDropDownList);

这假设您的产品类型下拉列表中已有一个value="abc"的元素。然后将自动预选该值。

我建议您使用另一种方法来渲染下拉列表。它包括删除视图数据和引入视图模型以及使用强类型版本的帮助程序:

public class ProductViewModel
{
    public string SelectedProductType { get; set; }
    public IEnumerable<SelectListItem> ProductTypes { get; set; }
}

然后您将拥有一个控制器操作,该操作将填充此视图模型并将其传递给视图:

public ActionResult SomeAction()
{
    var model = new ProductViewModel();

    // preselected an element with value = "type2"
    model.SelectedProductType = "type2";

    // bind the available product types
    model.ProductTypes = new SelectList(
        // Obviously those could come from a database or something
        new[] {
            new { Value = "type1", Text = "product type 1" },
            new { Value = "type2", Text = "product type 2" },
            new { Value = "type3", Text = "product type 3" },
            new { Value = "type4", Text = "product type 4" },
        }, 
        "Value", 
        "Text"
    );

    // pass the view model to the view
    return View(model);
}

最后在强类型视图中:

<%= Html.DropDownListFor(
    x => x.SelectedProductType, 
    Model.ProductTypes, 
    "defaultValue"
) %>