使用SelectList进行模型绑定 [英] Modelbinding with SelectList
问题描述
我使用Html.DropDownList(string NameSelectListInViewData)方法创建一个DropDown. 这将生成具有正确值的有效选择"输入.一切都很好.
I create a DropDown with the Html.DropDownList(string NameSelectListInViewData) method. This generates a valid Select input with the correct values. And all is well.
但是,提交后,源SelectList中的值未绑定.
Upon submit however, the value in the source SelectList is not bound.
案例: ViewData.SearchBag.FamilyCodes:
Case: ViewData.SearchBag.FamilyCodes:
public SelectList FamilyCodes { get; set; }
生成下拉列表的HTML
Html that generates the dropdown:
<%=Html.DropDownList("SearchBag.FamilyCodes")%>
生成的html:
<select id="SearchBag.FamilyCodes" name="SearchBag.FamilyCodes">
<option value=" ">Any</option>
<option value="A">BLUE</option>
<option value="B">BLACK</option>
<option value="C">BEIGE</option>
<option value="G">GREEN</option>
<option value="O">ORANGE</option>
<option value="P">PURPLE</option>
<option value="R">RED</option>
<option value="S">GRAY</option>
<option value="U">BROWN</option>
<option value="W">WHITE</option>
<option value="Y">YELLOW</option>
</select>
在我的控制器中,我有一个带有参数searchBag的动作.
In my controller I have an action with a parameter searchBag.
public ActionResult AdvancedSearch(SearchBag searchBag) {
//Do Stuff with parameters in searchBag
return View("AdvancedSearch", searchViewData);
}
所有其他字段都可以绑定,只有选择框不可以. 有什么想法吗?
All other fields bind just fine, only the selection boxes don't. Any ideas?
UPDATE
For future readers it might be worth it to read this blog post: http://haacked.com/archive/0001/01/01/model-binding-to-a-list.aspx
推荐答案
昨天在选择列表中遇到了类似的问题,该列表会生成很好的列表,只是在UpdateModel上会失败=-未绑定?
Had a similar issue yesterday with select lists, the list would generate fine, just that on UpdateModel- would fail =- not bound?
然后我在参数列表中找到了答案...
And i found the answer in the parameters list...
SelectList (
Collection - items to use in the drop down,
ValueField - ie the primarykey as a String,
NameField - ie the name of the thing as a String,
SelectedValue - which is the passed in current objects FK relationship)
所以对我来说...
Country = new SelectList(db.Countries,"pkCountry","CountryName",address.fkCountry);
Country = new SelectList(db.Countries, "pkCountry", "CountryName",address.fkCountry);
我使用ViewModel方法-并将其包含在视图模型的构造函数中...
I use the ViewModel approach - and have this in the constructor of the view Model...
public AddressCountryViewModel(){
public SelectList Countrys {get; private set;}
public AddressCountryViewModel(Address address)
{
Countrys = new SelectList(db.Countries, "pkCountry", "CountryName",address.fkCountry);
}
然后我在控制器 Edit Action 中获取值,并分配回要更新的对象...
I then grab the values in the controllers Edit Action and assign back to the object that is updating...
address.fkCountry = Convert.ToInt32(collection["fkCountry"]);
这篇关于使用SelectList进行模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!