2

鉴于以下视图模型和使用 的操作DefaultModelBinder,它似乎忽略了字典,但正确绑定了所有其他属性。我在这里错过了什么吗?查看 MVC 源代码,这似乎是合法的。

谢谢

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 输出为:

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

编辑:上面将不会像下面指出的那样工作,但是我更喜欢这种布局,下面的快速破解可以满足我的需要,在发布后调用它......

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

当然,它需要一些整理:)

4

1 回答 1

6

你可以看看这篇文章,看看应该如何绑定字典。恐怕使用强类型的EditorFor助手你将无法实现这一点,你将不得不手动生成字段。

于 2010-07-12T11:40:37.820 回答