为@ Html.DropDownList选择的值不起作用

时间:2017-02-22 11:52:09

标签: asp.net-mvc-4

未显示选定的drowdown值

@Html.DropDownListFor(x => x.AgeGroup, ViewBag.AgeGroup as SelectList, "Please select", new {@class = "form-control", id = "ddl_InvAgeGroup", name = "AgeGroup"} )

1 个答案:

答案 0 :(得分:0)

要获得所需的效果,您可以在视图模型上拥有2个属性:一个用于保存所选值,另一个用于保存可能值列表:

public class MyViewModel
{
    public string AgeGroup { get; set; }
    public IEnumerable<SelectListItem> AgeGroups { get; set; }
}

您将在控制器操作中填充:

public ActionResult Index()
{
    var model = new MyViewModel();

    // Obviously the list of possible values might be 
    // coming from a database or something else
    model.AgeGroups = new[]
    {
        new SelectListItem { Value = "1", Text = "group 1" },
        new SelectListItem { Value = "2", Text = "group 2" },
        new SelectListItem { Value = "3", Text = "group 3" },
    };

    // an element with Value="2" from the previous collection will be selected
    model.AgeGroup = "2";

    return View(model);
}

最后在你看来:

@Html.DropDownListFor(
    x => x.AgeGroup, 
    Model.AgeGroups, 
    "Please select", 
    new { @class = "form-control", id = "ddl_InvAgeGroup", name = "AgeGroup" }
)