Asp.net mvc 2模板没有前缀

den*_*s_n 2 asp.net-mvc asp.net-mvc-2

给出以下视图模型:

class DetailsViewModel
{
   public HeaderViewModel Header {get;set;}
   public FooterViewModel Footer {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Header视图模型的编辑器模板:

<%: Html.EditorFor(x => x.Header) %>
Run Code Online (Sandbox Code Playgroud)

编辑器模板(EditorTemplates/HeaderViewModel.ascx)

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

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

<%: Html.EditorFor(x => x.Search) %>
Run Code Online (Sandbox Code Playgroud)

结果:

<input type="text" value="" name="Search" id="Search" />
Run Code Online (Sandbox Code Playgroud)

如果我删除该行

<% ViewData.TemplateInfo.HtmlFieldPrefix = ""; %>
Run Code Online (Sandbox Code Playgroud)

结果是:

<input type="text" value="" name="Header.Search" id="Header_Search" />
Run Code Online (Sandbox Code Playgroud)

有没有另一种方法来实现相同 - 渲染没有前缀的控件的名称?

我在想一个帮手:

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();
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

<%: Html.EditorWithoutPrefix(Model.Header) %>
Run Code Online (Sandbox Code Playgroud)

但它抛出异常.

或许你知道另一种优雅的方式来呈现没有前缀的名字?

Dar*_*rov 6

你可以使用适当的过载:

<%: Html.EditorFor(x => x.Search, "SearchViewModel", "") %>
Run Code Online (Sandbox Code Playgroud)