asp.net-mvc ASP.NET MVC 2 - Html.DropDownList 与 ViewModel 混淆
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2306527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC 2 - Html.DropDownListFor confusion with ViewModel
提问by Sunday Ironfoot
I'm getting totally lost and confused on how to use the new strongly typed Html.DropDownListFor helper on ASP.NET MVC 2.0 R2
我对如何在 ASP.NET MVC 2.0 R2 上使用新的强类型 Html.DropDownListFor 助手完全迷失和困惑
In the View I'm writting:
在我写的视图中:
<%= Html.DropDownListFor(m => m.ParentCategory, new SelectList(Model.Categories, "CategoryId", "Name", Model.ParentCategory), "[ None ]")%>
<%= Html.ValidationMessageFor(m => m.ParentCategory)%>
and my Model object is thus:
因此我的模型对象是:
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; }
}
}
The problem is that when I select an item from the dropdown list, say the first item, I get the following ValidationMessageFor error "The value '1' is invalid."
问题是,当我从下拉列表中选择一个项目时,比如说第一个项目,我收到以下 ValidationMessageFor 错误“值 '1' 无效。”
So I change the View to...
所以我将视图更改为...
<%= Html.DropDownListFor(m => m.ParentCategory.**CategoryId**,
new SelectList .../ snip ) %>
Now it works, kinda. The ParentCategory property in my ViewModel is set with the correct 'CategoryId' but the 'Name' is NULL. Am I better off just having a nullable int for ParentCategory property instead of a strongly typed 'Category' object?
现在它起作用了,有点。我的 ViewModel 中的 ParentCategory 属性设置为正确的“CategoryId”,但“Name”为 NULL。我是否最好只为 ParentCategory 属性设置一个可为空的 int 而不是强类型的“Category”对象?
采纳答案by Rami A.
I was also experiencing the same issue.
我也遇到了同样的问题。
When I debug the Action and look at the ModelState.Values[1].Errors[0].Exception for example, I see the following:
例如,当我调试 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}
{"从类型'System.String'到类型'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]]' 失败,因为没有类型转换器可以在这些类型之间进行转换。"} System.Exception {System.InvalidOperationException}
In my scenario, my SelectList is created from a Dictionary and i use this in my view:
在我的场景中,我的 SelectList 是从字典创建的,我在我的视图中使用它:
<%=Html.DropDownListFor(x => x.MyDictionary,
new SelectList(
Model.MyDictionary,
"Value",
"Key")) %>
When I changed it to:
当我将其更改为:
<%=Html.DropDownListFor(x => x.MyDictionary.Keys, // <-- changed to .Keys
new SelectList(
Model.MyDictionary,
"Value",
"Key")) %>
It worked without issues.
它没有问题。
Thank you.
谢谢你。
回答by Edmon
<%= Html.DropDownListFor(m => m.ParentCategory,
new SelectList(
Model.Categories,
"CategoryId",
"Name",
Model.ParentCategory),
"[ None ]")%>
Did you try to use Model.ParentCategory.CategoryIdas a last parameter in SelectListand remove [None]parameter?
您是否尝试将其Model.ParentCategory.CategoryId用作最后一个参数SelectList并删除[None]参数?
回答by Per Hornsh?j-Schierbeck
I would get rid of
我会摆脱
public Category ParentCategory { get; set; }
and make a
并做一个
public int? CategoryId { get; set; }
instead. You probably only need the Id anyways - you could always look up the actual object using the Id as key (using a linq/lambda on your list in your case).
反而。无论如何,您可能只需要 Id - 您始终可以使用 Id 作为键查找实际对象(在您的情况下使用列表中的 linq/lambda)。
The view will then have these two:
该视图将具有以下两个:
<%= Html.DropDownListFor(m => m.CategoryId,
new SelectList(
Model.Categories,
"CategoryId",
"Name",
Model.CategoryId),
"[ None ]")%>
<%= Html.ValidationMessageFor(m => m.CategoryId)%>
回答by Gertjan
If the SelectList is null in the ViewModel I also received the above error
如果 ViewModel 中的 SelectList 为空,我也会收到上述错误
Make sure that the SelectList is set
确保设置了 SelectList

