且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVC5 - 如何设置“selectedValue"在 DropDownListFor Html 帮助器中

更新时间:2023-02-25 21:46:57

当您使用 DropDownListFor()(或 DropDownList())方法绑定到模型时属性,它是设置所选选项的属性值.

When you use the DropDownListFor() (or DropDownList()) method to bind to a model property, its the value of the property that sets the selected option.

在内部,这些方法生成自己的 IEnumerable 并根据属性值设置 Selected 属性,从而设置 Selected 代码中的属性将被忽略.只有当您不绑定到模型属性时才尊重它,例如使用

Internally, the methods generate their own IEnumerable<SelectListItem> and set the Selected property based on the value of the property, and therefore setting the Selected property in your code is ignored. The only time its respected is when you do not bind to a model property, for example using

@Html.DropDownList("NotAModelProperty", new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2))

注意你可以检查源代码,特别是 SelectInternal()GetSelectListWithDefaultValue() 方法,以了解其详细工作原理.

Note your can inspect the source code, in particular the SelectInternal() and GetSelectListWithDefaultValue() methods to see how it works in detail.

要在第一次渲染视图时显示选定的选项,请在将模型传递给视图之前在 GET 方法中设置属性的值

To display the selected option when the view is first rendered, set the value of the property in the GET method before you pass the model to the view

我还建议您的视图模型包含一个属性 IEnumerableTipoviDepozita 并在控制器中生成SelectList

I also recommend your view model contains a property IEnumerable<SelectListItem> TipoviDepozita and that you generate the SelectList in the controller

var model = new YourModel()
{
    TipoviDepozita = new SelectList(yourCollection, "Id", "Naziv"),
    TipPopustaId = 2 // set the selected option
}
return View(model);

所以视图变成

@Html.DropDownListFor(m => m.TipPopustaId, Model.TipoviDepozita, new { @class = "form-control" })