[英]DropDownListFor value not setting when creating new SelectList in view
Example #1 (this one works) Example#1(这个可行)
@Html.DropDownListFor(m => m.State.Id, Model.States)
I'm creating the SelectList in the controller for the first example like this. 我正在第一个这样的示例中在控制器中创建SelectList。
var states = Repository.GetStates();
var statesSelectList = new SelectList(states, "Id", "Name");
//model.States is a SelectList
model.States = statesSelectList;
Example #2 (this doesn't set the selected value on load) Example#2(这不会在加载时设置所选值)
@Html.DropDownListFor(m => m.State.Id, new SelectList(Model.States, "Id", "Name"))
I'm creating the SelectList in the view for the second example, and the controller looks like this. 我在第二个示例的视图中创建SelectList,控制器看起来像这样。
//model.States is a List<State>.
model.States = Repository.GetStates();
It seems there must be something simple that I'm missing. 似乎必须缺少一些简单的东西。 Let me know if I need to clarify anything else. 让我知道是否需要其他说明。 Thanks. 谢谢。
Add a property to your view model: 向您的视图模型添加属性:
private int? stateId;
public int StateId
{
get { return stateId ?? State.Id; }
set { stateId = value; }
}
Then in your Razor view: 然后在您的Razor视图中:
@Html.DropDownListFor(m => m.StateId, new SelectList(Model.States, "Id", "Name"))
And finally in your controller POST action: 最后在您的控制器POST操作中:
model.State = Repository.GetState(model.StateId);
Simple, yes. 很简单,是的。 Obvious no. 明显没有。 DropDownListFor
does not bind to nested objects like m => m.State.Id
. DropDownListFor
不会绑定到m => m.State.Id
类的嵌套对象。
It is designed for more basic relationships like m => m.Id
它设计用于更基本的关系,例如m => m.Id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.