dennis_n
dennis_n

Reputation: 802

Asp.net mvc 2 templates without prefix

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?

Upvotes: 2

Views: 1775

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

You could use the proper overload:

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

Upvotes: 6

Related Questions