我对如何在ASP.NET MVC 2.0 R2上使用新的强类型Html.DropDownListFor助手完全迷失了方向
在 View 中,我正在写:
<%= 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'无效”。
所以我将 View 更改为...
<%= Html.DropDownListFor(m => m.ParentCategory.**CategoryId**,
new SelectList .../ snip ) %>
现在可以了,有点。我的ViewModel中的ParentCategory属性设置为正确的“CategoryId”,但“名称”为NULL。我最好只为ParentCategory属性提供一个可为null的int而不是强类型的“Category”对象吗?
最佳答案
我也遇到了同样的问题。
当我调试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, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' failed because no type converter can convert between these types."} System.Exception {System.InvalidOperationException}
在我的场景中,我的SelectList是从Dictionary创建的,我在自己的 View 中使用它:
<%=Html.DropDownListFor(x => x.MyDictionary,
new SelectList(
Model.MyDictionary,
"Value",
"Key")) %>
当我将其更改为:
<%=Html.DropDownListFor(x => x.MyDictionary.Keys, // <-- changed to .Keys
new SelectList(
Model.MyDictionary,
"Value",
"Key")) %>
它没有问题。
谢谢。
关于asp.net-mvc - ASP.NET MVC 2-Html.DropDownList用于与ViewModel混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2306527/