Mvc,Selectlist选择对象值

时间:2017-05-02 12:15:05

标签: asp.net-mvc razor

我有这个选择列表:

控制器:

 ViewBag.SagId = new SelectList(db.Sags, "Id", "Emne", 7);

列表和所有内容都适用于,但所选值不是== 7,

查看:

 @Html.DropDownListFor(x => x.SagId,(IEnumerable<SelectListItem>) ViewBag.SagId,
new
{

    @class = "selectpickers",
    data_show_subtext = "true",
    data_live_search = "true"

})

可能是我错过了一些愚蠢的事情?

1 个答案:

答案 0 :(得分:0)

模型绑定通过绑定到模型属性的值来工作。在将模型传递给视图之前,需要在控制器中设置属性SagId的值。

您的控制器方法中的代码应该类似于

var model = new YourModel()
{
    SagId = 7
};
ViewBag.SagId = new SelectList(db.Sags, "Id", "Emne");
return View(model);

请注意,SelectList构造函数中没有设置第4个参数的点。绑定到模型属性时会忽略它,因为DropDownListFor()方法在内部构建自己的IEnumerable<SelectListItem>并根据绑定的属性值设置Selected属性。 / p>

另请注意,您不应对绑定的属性使用相同的名称(请参阅Can the ViewBag name be the same as the Model property name in a DropDownList?),我强烈建议您使用视图模型,尤其是在编辑时,视图模型将包含属性public IEnumerable<SelectListItem> SagList { get; set; },在视图中它将是@Html.DropDownListFor(m => m.SagId, Model.SagList, new { ... })

相关问题