在视图中我写:
<%= Html.DropDownListFor(m => m.ParentCategory,new SelectList(Model.Categories,"CategoryId","Name",Model.ParentCategory),"[ None ]")%> <%= Html.ValidationMessageFor(m => m.ParentCategory)%>
因此我的Model对象是:
public class CategoryForm : FormModelBase { public CategoryForm() { Categories = new List<Category>(); Categories.Add(new CategoryForm.Category() { CategoryId = 1,Name = "CPUs" }); Categories.Add(new CategoryForm.Category() { CategoryId = 2,Name = "Memory" }); Categories.Add(new CategoryForm.Category() { CategoryId = 3,Name = "Hard drives" }); } // ...other props,snip... // public Category ParentCategory { get; set; } public IList<Category> Categories { get; protected set; } public class Category { public int? CategoryId { get; set; } public string Name { get; set; } } }
问题是,当我从下拉列表中选择一个项目,说第一个项目,我得到以下ValidationMessageFor错误“值’1’无效。
所以我将视图更改为…
<%= Html.DropDownListFor(m => m.ParentCategory.**CategoryId**,new SelectList .../ snip ) %>
现在它工作,有点。我的ViewModel中的ParentCategory属性设置了正确的“CategoryId”,但“Name”为NULL。我最好只有一个可空的int ParentCategory属性,而不是一个强类型的’类’对象?
解决方法
当我调试Action并看看ModelState.Values [1] .Errors [0] .Exception例如,我看到以下:
{“The parameter conversion from type ‘System.String’ to type ‘System.Collections.Generic.KeyValuePair`2[[System.String,mscorlib,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089],[System.Int64,PublicKeyToken=b77a5c561934e089]]’ failed because no type converter can convert between these types.”} System.Exception {System.InvalidOperationException}
在我的场景中,我的SelectList是从字典创建的,我在我的视图中使用:
<%=Html.DropDownListFor(x => x.MyDictionary,new SelectList( Model.MyDictionary,"Value","Key")) %>
当我把它改为:
<%=Html.DropDownListFor(x => x.MyDictionary.Keys,// <-- changed to .Keys new SelectList( Model.MyDictionary,"Key")) %>
它工作没有问题。
谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。