我尝试将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的内容在视图中看起来很好,但是当我回发post时,绑定不起作用,目录仍然是空的。
发布于 2013-01-30 02:49:19
与此同时,我找到了解决方案。
我可以将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-26 23:43:47
概念
要绑定字典,必须更改html input标记中的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的HiddenFor和TextBoxFor HTML Helper。
@Html.HiddenFor(model => model[i].Key)
@Html.TextBoxFor(model => model[i].Value)它将以asp.net mvc能够理解的格式呈现,并使其正常工作。
有关数据库绑定的更多示例,请查看this link。
https://stackoverflow.com/questions/14537126
复制相似问题