强制EditorFor在视图上使用类名为输入项添加前缀?
我有一个EditorFor:
model.Client, "ClientTemplate", new { editing = false })%>
这将绑定到视图正常(如预期)但在模型发布时不会绑定绑定。 这是因为表单id没有以“Client”为前缀。
通常在这种情况下,我只是传入模型,然后将输入绑定到模板中的model.Client.PropertyName,但在这种情况下,这不是一个选项,因为模板用于两个不同的视图模型(有客户端)。
有关正确绑定的任何建议吗?
非常感谢,Kohan。
附录
这似乎是我的一个误解,我现在明白这个问题是fluentHtml在EditorFor Templates中不起作用。 (同样适用于此修复,因为事实certificate不需要,因为如果我用正常的mvc html助手替换fluentHtml,EditorFor会自动为我添加前缀)
尝试以下方法:
<% Html.BeginHtmlFieldPrefixScope("Client") { Html.EditorFor(model => model.Client, "ClientTemplate", new { editing = false }); <% } %>
使用EditorFor,LabelFor等制作的每个字段都将作为前缀。
编辑:这是我正在使用的扩展方法,抱歉!
public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix) { return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix); }
……和class级……
private class HtmlFieldPrefixScope : IDisposable { private readonly TemplateInfo templateInfo; private readonly string previousHtmlFieldPrefix; public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix) { this.templateInfo = templateInfo; previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix; templateInfo.HtmlFieldPrefix = htmlFieldPrefix; } public void Dispose() { templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix; } }
请参阅以下评论中Kohan提到的链接。
MVC3 HTML名称冲突
切割和粘贴在MVC3中不起作用。 为了使扩展能够工作,我必须创建一个类文件:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace incMvcSite.Classes { public static class HtmlPrefixScopeExtensions { public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix) { return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix); } private class HtmlFieldPrefixScope : IDisposable { private readonly TemplateInfo templateInfo; private readonly string previousHtmlFieldPrefix; public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix) { this.templateInfo = templateInfo; previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix; templateInfo.HtmlFieldPrefix = htmlFieldPrefix; } public void Dispose() { templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix; } } } }
在Razor(.cshtml)文件中,我添加了以下内容:
@using incMvcSite.Classes @using(Html.BeginHtmlFieldPrefixScope("Permission")) { }
注意使用将扩展类带入范围。 这允许第二个使用线工作。
现在的问题是,在回发时,对象不会更新。 在我的控制器中,我使用第二个参数来指定我的前缀:
TryUpdateModel(modelUser.Permission, "Permission");
这为HTML中的所有字段添加了前缀,TryUpdateModel使用前缀控件名称加载了对象。 现在,您可以正确命名嵌入式编辑列表的控件,以及具有相同属性名称的模型的部分视图。