本文介绍了在创建新视图时的SelectList价值DropDownListFor不设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
【举例】#1(这个工作)
Example #1 (this one works)
@Html.DropDownListFor(m => m.State.Id, Model.States)
我的控制器中像这样的第一个例子创建选择列表。
I'm creating the SelectList in the controller for the first example like this.
var states = Repository.GetStates();
var statesSelectList = new SelectList(states, "Id", "Name");
//model.States is a SelectList
model.States = statesSelectList;
例2(这不设置负载所选值)
Example #2 (this doesn't set the selected value on load)
@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.
//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; }
}
然后在您的Razor视图:
Then in your Razor view:
@Html.DropDownListFor(m => m.StateId, new SelectList(Model.States, "Id", "Name"))
最后在你的控制器POST操作:
And finally in your controller POST action:
model.State = Repository.GetState(model.StateId);
这篇关于在创建新视图时的SelectList价值DropDownListFor不设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!