asp.net-mvc – ASP.NET MVC 3中字典的隐藏输入
发布时间:2020-12-16 06:47:37 所属栏目:asp.Net 来源:网络整理
导读:我需要在Post动作中获取我的模型属性,因此需要为它们隐藏元素,但我对Dictionary string,string的类型有问题.这是我的模特: public class ViewModel{ ... public ViewPart ViewPart { get; set; }}public class ViewPart { ... public Dictionarystring,stri
我需要在Post动作中获取我的模型属性,因此需要为它们隐藏元素,但我对Dictionary< string,string>的类型有问题.这是我的模特:
public class ViewModel{ ... public ViewPart ViewPart { get; set; } } public class ViewPart { ... public Dictionary<string,string> Flags { get; set; } } 和我的控制器: Dictionary<string,string> flags = new Dictionary<string,string>(); flags.Add("kind","Edit"); flags.Add("Command","Save"); ViewModel model = new ViewModel(){ Flags = flags }; return View(model); 在视图中: @foreach(var item in Model.ViewPart.Flags) { <input type="hidden" id="ViewPart_Flags_@(item.Key)" value="@item.Value" name="ViewPart.Flags[@(item.Key)]" /> } 我也尝试这个: @foreach(var item in Model.ViewPart.Flags) { @Html.HiddenFor(modelItem => item) } 更新 [HttpPost] public ActionResult MyPostAction(ViewModel model){ //model.ViewPart.Flags is null } 但是在Post动作中,Flags总是为null,为什么呢?我的错在哪里?有没有更好的方法从View To Action传递变量? 解决方法
如果要将模型绑定到字典,则需要两个隐藏字段,一个用于Key,另一个用于Value:
var index = 0; foreach (var item in Model.ViewPart.Flags) { <input type="hidden" value="@item.Key" name="ViewPart.Flags[@(index)].Key"/> <input type="hidden" value="@item.Value" name="ViewPart.Flags[@(index)].Value"/> index++; } <input type="submit" value="Save"/> 注意,您还需要一个运行索引来使模型绑定器满意. 或者,如果您不想运行,可以使用附加隐藏的索引字段来解决: foreach (var item in Model.ViewPart.Flags) { <input type="hidden" value="@item.Key" name="ViewPart.Flags.Index"/> <input type="hidden" value="@item.Key" name="ViewPart.Flags[@(item.Key)].Key" /> <input type="hidden" value="@item.Value" name="ViewPart.Flags[@(item.Key)].Value" /> } <input type="submit" value="Save"/> } 在这两篇文章中,您可以找到许多关于使用集合进行模型绑定的信息: > ASP.NET Wire Format for Model Binding to Arrays,Lists,Collections,Dictionaries (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc-5 – 更改消息“密码必须至少包含一个非字母或
- asp.net-mvc-4 – 如果使用实体连接字符串(与SQL连接字符串
- asp.net-mvc-4 – 将项目升级到MVC 5
- asp.net-mvc – HTTP错误500.19 – 内部服务器错误 – syst
- asp.net – 在Visual Studio 2012中创建控制器时出错
- 使用.NET 4.5的ASP.Net成员身份和实体框架迁移的问题
- asp.net-mvc – 关于asp.net MVC视图模型模式的几个问题
- asp.net-mvc – 将集合传递给EditorFor()时,它会为输入元素
- asp.net – HttpServerUtility.UrlPathEncode vs HttpServe
- 一步步开发自己的博客 .NET版(3、注册登录功能)
推荐文章
站长推荐
- asp.net – Mono vhost配置错误:地址已经在使用
- Apppool回收和带有线程的Asp.net?
- Asp.net Core 1.1 升级后操作mysql出错的解决办法
- AspNetCore.Authentication.JwtBearer失败,没有S
- ASP.NET:获取页面的文件名
- 深蓝词库转换1.9发布——支持英库拼音
- asp.net-core-2.1 – 配置HttpClientFactory以使
- 如何在ASP.NET中注入包含&符号的脚本URL?
- asp.net-mvc – 使用KendoUI Grid的KendoUI编辑器
- asp.net-mvc – 在MVC4中路由具有扩展名的url将无
热点阅读