Question

I am using editor templates in my code and what I noticed is that lot of the controls get the name property set based on index.

@Html.EditorFor(x => x.Emails)

Where Answers is collection of EmailViewModel object

What gets rendered is this for each of item:

<input data-val="true" data-val-number="The field must be a number." 
      data-val-required="The Email field is required." 
      id="Emails_0__EmailId" name="Emails[0].EmailId" value="1">

I tried to set the name property like this:

@Html.TextBoxFor(x => x.EmailId, new { @name = "EmailAdress" })

But this has no effect!

What do I need to do so it takes name value in effect. The main reason for doing this is for validation purposes. In my validation rules I have the following:

$("#someForm").validate({
        rules: {
            EmailAddress: {
                required: true,
                email: true
            }
        }
    });
Was it helpful?

Solution

Try

@Html.EditorFor(x => x.Emails, "string", "EmailAddress") //or EmailAdress

MSDN reference has the following, you are interested in the htmlFieldName

public static MvcHtmlString EditorFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression,
    string templateName,
    string htmlFieldName
)

A string that is used to disambiguate the names of HTML input elements that are rendered for properties that have the same name.

To edit the prefix you can set this in your controller

ViewData.TemplateInfo.HtmlFieldPrefix

or in your view

@Html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "Foo"

Of course you could write your own helper that does this wherever you use it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top