asp.net-mvc – 如何在ASP.NET MVC上为GET和POST操作绑定Diction
发布时间:2020-12-16 09:22:52 所属栏目:asp.Net 来源:网络整理
导读:我想定义一个显示标签和复选框列表的视图,用户可以更改复选框,然后回发.我在回复字典时遇到问题.也就是说,post方法的字典参数为null. 以下是GET和POST操作的操作方法: public ActionResult MasterEdit(int id) { Dictionarystring,bool kv = new Dictionary
我想定义一个显示标签和复选框列表的视图,用户可以更改复选框,然后回发.我在回复字典时遇到问题.也就是说,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" /> } 任何想法都将非常感谢! 解决方法
不要为此使用字典.它们与模型绑定不匹配.可能是PITA.
视图模型更合适: public class MyViewModel { public string Id { get; set; } public bool Checked { get; set; } } 然后一个控制器: public class HomeController : Controller { public ActionResult Index() { var model = new[] { new MyViewModel { Id = "A",Checked = true },new MyViewModel { Id = "B",Checked = false },}; return View(model); } [HttpPost] public ActionResult Index(IEnumerable<MyViewModel> model) { return View(model); } } 然后是相应的视图(?/ Views / Home / Index.cshtml): @model IEnumerable<MyViewModel> @using (Html.BeginForm()) { <table> <thead> <tr> <th></th> </tr> </thead> <tbody> @Html.EditorForModel() </tbody> </table> <input type="submit" value="Save" /> } 最后是相应的编辑器模板(?/ Views / Home / EditorTemplates / MyViewModel.cshtml): @model MyViewModel <tr> <td> @Html.HiddenFor(x => x.Id) @Html.CheckBoxFor(x => x.Checked) @Html.DisplayFor(x => x.Id) </td> </tr> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 为什么ASP.Net MVC(或CodeIgniter)中没有内
- asp.net-mvc – ASP.Net MVC尝试抓住最佳实践
- asp.net-mvc – 如何在MVC中调用.ashx文件?
- 使用带有asp.net.No错误消息的SalesLogix使用OleDb连接时出
- asp.net部署到IIS常见问题的解决方法
- asp.net – 如何在gridview中将navigateurl添加到超链接
- 如何使ASP.NET MVC应用程序多语言?
- asp.net – 在回发上设置viewstate
- asp.net – 获取隐藏字段的值
- 如何在回发期间在asp.net mvc中保留部分视图模型数据
推荐文章
站长推荐
- ASP.NET CORE 使用 EF CORE访问数据库
- asp.net-mvc – “继承”ASP.NET MVC网站从一个常
- 在ASP.NET C#中抛出异常
- 当会话状态超时在asp.net mvc中完成时,如何重定向
- asp.net – 为什么我的项目引用不被Visual Studi
- asp.net-mvc – asp.net mvc针对不同操作的不同验
- asp.net-mvc – Autofac,MVC(带ActionFilters),W
- asp.net-mvc – 防止用户在asp.net模型验证中输入
- ASP.Net 4.0可以设置为使用ASP.Net 2.0的根网站的
- asp.net – 依赖注入:在aspx页面中注入用户控件
热点阅读