鉴于使用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);
它需要一些整理过程:)