2010-07-12 58 views
1

鑑於以下視圖模型和使用DefaultModelBinder的操作,它似乎忽略字典,但正確綁定所有其他屬性。我在這裏錯過了什麼嗎?看着MVC源代碼,這似乎是合法的。ASP.NET 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); 

它需要一些清理c ourse :)

回答

6

你可以看看this post看看字典應該如何綁定。我害怕使用強類型的EditorFor助手,你將無法實現這一點,你將不得不手動生成字段。

+0

啊哈,我明白了,謝謝!我不太喜歡這種佈局,但是我有一個非常快速的黑客機制,可以滿足我的需求,我會在上面發佈它。 – amarsuperstar 2010-07-12 11:52:02