[英]Override ASP.NET MVC EditorFor
Is it possible to override ASP.NET MVC's EditorFor
and DisplayFor
. 是否可以覆盖ASP.NET MVC的
EditorFor
和DisplayFor
。
I want to apply some logic as to whether or not to actually display the content or simply output "". 我想应用一些逻辑来确定是否实际显示内容或只是输出“”。
So I want to do something like this (pseudocode): 所以我想做这样的事情(伪代码):
public static MyEditorFor(this html)
{
if(ICanRender)
{
call HtmlEditorFor(original);
}
else
{
return EmtpyString;
}
}
Is this possible? 这可能吗?
It sound like you want an extension: 这听起来像你想要一个扩展:
public static MvcHtmlString MyEditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {
if(ICanRender)
{
return System.Web.Mvc.Html.EditorExtensions.EditorFor(html, expression);
}
else
{
return MvcHtmlString.Create(string.Empty);
}
}
That codesnipped is untested but it should work. 编码未经测试但应该可行。
You can create your own Html helpers as extensions methods for HtmlHelper
or HtmlHelper<TModel>
. 您可以创建自己的Html助手作为
HtmlHelper
或HtmlHelper<TModel>
扩展方法。 Simply add extension method like below: 只需添加如下扩展方法:
public static MvcHtmlString MyEditorFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
}
Of course, you can add additional parameters as needed. 当然,您可以根据需要添加其他参数。 Inside this method access all methods of
htmlHelper
. 在此方法内部访问
htmlHelper
所有方法。 Return ordinary EditorFor
for example: 返回普通
EditorFor
器例如:
public static MvcHtmlString MyEditorFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
return htmlHelper.EditorFor(expression);
}
Or you can create your own element (or combination of them) as you need: 或者您可以根据需要创建自己的元素(或它们的组合):
public static MvcHtmlString MyEditorFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
TagBuilder div = new TagBuilder("div");
div.AddCssClass("some-css");
MvcHtmlString editor = htmlHelper.TextBoxFor(expression);
div.InnerHtml = editor.ToHtmlString();
return new MvcHtmlString(div.ToString());
}
You could put the custon models under the "views/shared/EditorTemplates" or "views/shared/DisplayTemplates", and put the files with the [Model name].cshtml. 您可以将custon模型放在“views / shared / EditorTemplates”或“views / shared / DisplayTemplates”下,并将文件放在[Model name] .cshtml中。
Ex: DateTime.cshtml 例如:DateTime.cshtml
That way all editors and displays with DateTime type defined in your models properties will follow the DateTime.cshtml logic. 这样,在模型属性中定义的具有DateTime类型的所有编辑器和显示都将遵循DateTime.cshtml逻辑。
The problem is you will have to deal with the HTML in the ViewData.TemplateInfo if you want to retrieve the fields you want. 问题是,如果要检索所需的字段,则必须处理ViewData.TemplateInfo中的HTML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.