0

我尝试将 an 绑定OrderedDictionary到视图,但是当调用 post 方法时,Dictionary 始终为空。

这是我的代码:

    [HttpGet]
    public ViewResult Edit(string username, string password)
    {
        Xml test = new Xml(@"c:\Users\pc\Desktop\xml - Copy.xml");
        XmlNode userNode = test.GetUserNodeByUsernameAndPassword(username, password);
        User user = new User();
        user.BindData(userNode);
        return View(user.user);
    }

    [HttpPost]
    public ViewResult Edit(OrderedDictionary attributes)
    {
        return View(attributes);
    }

这是视图:

@using (Html.BeginForm("Edit", "Users")) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>User</legend>

    <p>
        <input type="submit" value="Save" />
    </p>

    @{int counter = 0;}
    @{string name = "";}
    @foreach (DictionaryEntry attribute in Model)
    {
        { name = "[" + counter + "].key"; }
        <input type="hidden" name=@name value=@attribute.Key />
        @attribute.Key @Html.TextBoxFor(m => attribute.Value)
        counter++;
        <br />
    }
</fieldset>
}

结果 Html 看起来像这样:

<input type="hidden" value="Username" name="[0].key">
  Username
  <input id="attribute_Value" type="text" value="Anamana" name="attribute.Value">

因此,OrderedDictionary视图中的内容看起来很好,但是当我发回帖子时,绑定不起作用并且目录保持为空。

4

2 回答 2

1

概念

要绑定字典,您必须更改 html 输入标签中的 name 属性。像这样的东西:

在您的控制器中:

[HttpPost]
public ActionResult Edit(IDictionary<string, string> attributes) 
{  
}

在您的 HTML 中:

<input type="text" name="attributes[0].Key" value="A Key" />
<input type="text" name="attributes[0].Value" value="A Value" />

<input type="text" name="attributes[1].Key" value="B Key" />
<input type="text" name="attributes[1].Value" value="B Value" />

attributes名称应该在[0]名称属性的索引之前,因为您的操作期望它。

尖端

我会使用 Asp.Net MVC 的HiddenForHTML TextBoxForHelper。

@Html.HiddenFor(model => model[i].Key)
@Html.TextBoxFor(model => model[i].Value)

它将以 asp.net mvc 可以理解并使其工作的格式呈现。

有关数据绑定的更多示例,请查看此链接

于 2013-01-26T15:43:46.780 回答
0

与此同时,我找到了解决方案。

我可以将一个传递OrderedDictionary给视图页面。它通过以下Razor代码处理它:

    @model System.Collections.Specialized.OrderedDictionary
    (...)
    @{int counter = 0;}
    @{string name = "";}
    @foreach (DictionaryEntry attribute in Model)
    {
        { name = "[" + counter + "].key"; }
        @Html.Hidden(name, attribute.Key)
        {name = "[" + counter + "].value";}
        @attribute.Key @Html.TextBox(name, attribute.Value)
        counter++;
        <br />
    }

结果HTML的结构适合书中的样本,字典中的值在页面上显示得很好。

调用 POST 后,POST 处理程序函数在Dictionary.

    [HttpPost]
    public ViewResult Edit(Dictionary<string, string> attributes)
    {}

我不知道为什么,但我不能OrderedDictionary在这里使用。

于 2013-01-29T18:49:18.927 回答