如何在 ASP.NET MVC 上为 GET 和 POST 操作绑定字典类型参数
我想定义一个显示标签和复选框列表的视图,用户可以更改复选框,然后发回。我在回传字典时遇到问题。也就是说,post方法的字典参数为null。
以下是 GET 和 POST 操作的操作方法:
public ActionResult MasterEdit(int id)
{
Dictionary<string, bool> kv = new Dictionary<string, bool>()
{
{"A", true},
{"B", false}
};
return View(kv);
}
[HttpPost]
public ActionResult MasterEdit(Dictionary<string, bool> kv)
{
return RedirectToAction("MasterEdit", new { id = 1 });
}
Beliw 是视图
@model System.Collections.Generic.Dictionary<string, bool>
@{
ViewBag.Title = "Edit";
}
<h2>
MasterEdit</h2>
@using (Html.BeginForm())
{
<table>
@foreach(var dic in Model)
{
<tr>
@dic.Key <input type="checkbox" name="kv" value="@dic.Value" />
</tr>
}
</table>
<input type="submit" value="Save" />
}
任何想法将不胜感激!
I want to define a view which displays a list of label and checkbox, user can change the checkbox, then post back. I have problem posting back the dictionary. That is, The dictionary parameter for the post method is null.
Below are action method for both GET and POST action:
public ActionResult MasterEdit(int id)
{
Dictionary<string, bool> kv = new Dictionary<string, bool>()
{
{"A", true},
{"B", false}
};
return View(kv);
}
[HttpPost]
public ActionResult MasterEdit(Dictionary<string, bool> kv)
{
return RedirectToAction("MasterEdit", new { id = 1 });
}
Beliw is the view
@model System.Collections.Generic.Dictionary<string, bool>
@{
ViewBag.Title = "Edit";
}
<h2>
MasterEdit</h2>
@using (Html.BeginForm())
{
<table>
@foreach(var dic in Model)
{
<tr>
@dic.Key <input type="checkbox" name="kv" value="@dic.Value" />
</tr>
}
</table>
<input type="submit" value="Save" />
}
Any idea would be very much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要为此使用字典。它们不能很好地处理模型绑定。可能是皮塔饼。
视图模型会更合适:
然后是控制器:
然后是相应的视图(
~/Views/Home/Index.cshtml
):最后是相应的编辑器模板(
~/Views/Home /EditorTemplates/MyViewModel.cshtml
):Don't use a dictionary for this. They don't play well with model binding. Could be a PITA.
A view model would be more appropriate:
then a controller:
then a corresponding view (
~/Views/Home/Index.cshtml
):and finally the corresponding editor template (
~/Views/Home/EditorTemplates/MyViewModel.cshtml
):请查看 scott hanselman 的这篇文章。有模型绑定到字典、列表等的示例
Take a look at this post by scott hanselman. There're the examples of model binding to a dictionary, lists, etc