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")) {
<fieldset>
<legend>Permission</legend>
// The Html.EditorFor's would go here...
</fieldset>
}
注意使用将我的扩展类带入范围。这允许第二个使用线工作。
现在的问题是回发时,对象没有更新。在我的控制器中,我使用了第二个参数来指定我的前缀:
TryUpdateModel(modelUser.Permission, "Permission");
这为 HTML 中的所有字段添加了前缀,并且 TryUpdateModel 加载了带有前缀控件名称的对象。现在,您可以为嵌入式编辑列表和具有相同属性名称的模型的部分视图正确命名控件。