2

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?

6
  • 3
    Just curious, why do you want to remove the prefix? The prefix is what enables the model binder to do its job correctly when the form is posted to the server. Commented Jan 4, 2011 at 13:40
  • I hate the idea of using Bind(Prefix=...) attribute. Commented Jan 4, 2011 at 14:04
  • Can't you just use HTML.Editor("Search")? Commented Jan 4, 2011 at 15:36
  • @Brian Ball, what if you want the POST action to take HeaderViewModel as parameter instead of DetailsViewModel? In this case you need to remove the prefixes. Commented Jan 5, 2011 at 7:41
  • @Darin Dimitrov, I was thinking that is what denis_n was getting at, but I wanted to be sure. @denis_n, look below, I believe I have an answer for you. Commented Jan 5, 2011 at 13:31

1 Answer 1

6

You could use the proper overload:

<%: Html.EditorFor(x => x.Search, "SearchViewModel", "") %>
Sign up to request clarification or add additional context in comments.

2 Comments

I believe if you pass in null instead of "SearchViewModel", then MVC will use the default behavior of looking for an editor template.
this has nothing related to removing the Header prefix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.