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 に答える