ASP.NET MVC Model Binder not working with a dictionary

穿精又带淫゛_ 提交于 2019-12-24 07:54:47

问题


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.

Thanks

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>

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="" />

EDIT: 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);

It needs some tidying up ofcourse :)


回答1:


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.



来源:https://stackoverflow.com/questions/3228099/asp-net-mvc-model-binder-not-working-with-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!