加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC 2 – Html.DropDownList与ViewModel

发布时间:2020-12-15 19:35:07 所属栏目:asp.Net 来源:网络整理
导读:我完全迷失了,如何使用新的强类型Html.DropDownListFor帮助ASP.NET MVC 2.0 R2 在视图中我写: %= Html.DropDownListFor(m = m.ParentCategory,new SelectList(Model.Categories,"CategoryId","Name",Model.ParentCategory),"[ None ]")%%= Html.Validation
我完全迷失了,如何使用新的强类型Html.DropDownListFor帮助ASP.NET MVC 2.0 R2

在视图中我写:

<%= 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")) %>

它工作没有问题。

谢谢。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读