ASP.NET MVC模型绑定不借助词典工作 [英] ASP.NET MVC Model Binder not working with a dictionary

查看:189
本文介绍了ASP.NET MVC模型绑定不借助词典工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于使用 DefaultModelBinder ,它似乎忽视了字典,但正确绑定所有其他属性以下视图模型和行动。我失去了一些东西在这里?在MVC源$ C ​​$寻找C此似乎合法的。

Given the following view model and action using the DefaultModelBinder, it seems to ignore the dictionary, but bind all other properties correctly. Am I missing something here? Looking at the MVC source code this seems legit.

感谢

public class SomeViewModel
{
    public SomeViewModel()
    {
        SomeDictionary = new Dictionary<string, object>();
    }

    public string SomeString { get; set; }
    public IDictionary<string, object> SomeDictionary { get; set; }
}

[HttpPost]
public ActionResult MyAction(SomeViewModel someViewModel)
{
    //someViewModel.SomeString binds correctly
    //someViewModel.SomeDictionary is null
}

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<SomeViewModel>" MasterPageFile="~/Views/Shared/Site.Master" %>
<asp:Content runat="server" ID="Content2" ContentPlaceHolderID="MainContent">
<% using (Html.BeginForm("MyAction", "MyController")) {%>

    <%= Html.EditorFor(m => m.SomeString) %>
    <%= Html.EditorFor(m => m.SomeDictionary["somevalue"]) %>

    <input type="submit" value="Go" />
<%} %>
</asp:Content>

和参考,HTML输出是:

And for reference, the HTML output is:

<input class="text-box single-line" id="SomeString" name="SomeString" type="text" value="" />
<input class="text-box single-line" id="Somedictionary_somevalue_" name="SomeDictionary[somevalue]" type="text" value="" />

编辑:以上是行不通的,如下指出的,但是我preFER这种布局及以下快速劈适用于我的需求,把这个刚刚发布后...

The above will not work as pointed out below, however I prefer this layout and the following quick hack works for my needs, call this just after posting...

someViewModel.SomeDictionary = (from object key in Request.Form.Keys
                                where key.ToString().StartsWith("SomeDictionary[")
                                select new
                                {
                                    Key = key.ToString().Replace("SomeDictionary[", string.Empty).Replace("]", string.Empty),
                                    Value = (object)Request.Form[key.ToString()]
                                }).ToDictionary(arg => arg.Key, arg1 => arg1.Value);

这需要一定的整理ofcourse:)

It needs some tidying up ofcourse :)

推荐答案

您可以看看<一个href=\"http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx\">this帖子看看字典应该如何绑定。恐怕使用强类型 EditorFor 助手,你将无法实现这一点,你必须手动生成的字段。

You may take a look at this post to see how dictionaries should be binded. I am afraid that using strongly typed EditorFor helpers you won't be able to achieve this and you will have to generate the fields manually.

这篇关于ASP.NET MVC模型绑定不借助词典工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆