如何绑定有序字典
本文关键字:字典 绑定 何绑定 | 更新日期: 2023-09-27 17:56:12
我尝试将OrderedDictionary
绑定到视图,但是当调用post方法时,字典始终为空。
这是我的代码:
[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
的内容在视图中看起来很好,但是当我进行回发时,绑定不起作用,目录仍然为空。
概念
要绑定字典,您必须更改 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
名称应位于 name 属性的索引[0]
之前,因为您的操作需要它。
技巧
我会使用 Asp.Net MVC的HiddenFor
和TextBoxFor
HTML助手。
@Html.HiddenFor(model => model[i].Key)
@Html.TextBoxFor(model => model[i].Value)
它将以 asp.net mvc 可以理解并使其正常工作的格式呈现。
有关数据绑定的更多示例,请查看此链接。
与此同时,
我找到了解决方案。
我可以将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 处理程序函数在Dictionary
中获取修改后的值。
[HttpPost]
public ViewResult Edit(Dictionary<string, string> attributes)
{}
我不知道为什么,但我不能在这里使用OrderedDictionary
。