Asp.net mvc 2 templates without prefix

痴心易碎 提交于 2019-12-10 10:37:11

问题


Given following view model:

class DetailsViewModel
{
   public HeaderViewModel Header {get;set;}
   public FooterViewModel Footer {get;set;}
}

I'm using editor template for Header view model:

<%: Html.EditorFor(x => x.Header) %>

The editor template (EditorTemplates/HeaderViewModel.ascx)

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<HeaderViewModel>" %>

<% ViewData.TemplateInfo.HtmlFieldPrefix = ""; %>

<%: Html.EditorFor(x => x.Search) %>

The result:

<input type="text" value="" name="Search" id="Search" />

If I remove the line

<% ViewData.TemplateInfo.HtmlFieldPrefix = ""; %>

the result is:

<input type="text" value="" name="Header.Search" id="Header_Search" />

Is there another way to achieve the same - render the names of the control without prefix?

I was thinking about a helper:

public static MvcHtmlString EditorWithoutPrefix<TModel, TValue>(
  this HtmlHelper<TModel> html, TValue value)
{
  var htmlHelper =... // create new HtmlHelper<TValue> and set it's model to be 'value' argument

  return htmlHelper.EditorForModel();
}

and use it:

<%: Html.EditorWithoutPrefix(Model.Header) %>

but it is throwing exceptions.

Or maybe you know another elegant way to render names without prefix?


回答1:


You could use the proper overload:

<%: Html.EditorFor(x => x.Search, "SearchViewModel", "") %>


来源:https://stackoverflow.com/questions/4594190/asp-net-mvc-2-templates-without-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!