views:

185

answers:

1

ASP.NET MVC 2 Dots Replaced With Underscore In Element Name (even though ASP.NET MVC will put dots in by default in the name attribute!)

When you stick an element on a form in ASP.NET MVC, it usually does the following:

<%= Html.TextBoxFor(model => model.Contact.FirstName)%>

Becomes

<input type="text" name="Contact.FirstName" id="Contact_FirstName" ...

This is all well and good. However, if you then want to do this:

<%= Html.DropDownList(
    "Contact_Title",
    new SelectList(Model.Titles, "Key", "Value"))%>

You actually end up with

<select id="Contact_Title" name="Contact_Title">...

Note that you now have an underscore not a dot in the name attribute.

So I thought I'd pass in the name, including a dot, like this:

<%= Html.DropDownList(
    "Contact_Title", 
    new SelectList(Model.Titles, "Key", "Value"),
    new { name = "Contact\\.Title" })%>

But it still renders as:

<select id="Contact_Title" name="Contact_Title">...

I really (really) want this to render as:

<select id="Contact_Title" name="Contact.Title">...

In order for this to bind back to Model.Contact.Title automatically - any ideas?

IMPORTANT UPDATE

This is slightly different to my initial thoughts... it actually looks like whatever I pass as the name attribute is simply ignored...

new { name = "MYNAME" }

Still results in Contact_Title!

Any help appreciated!

+5  A: 
<%= Html.DropDownList(
    "Contact.Title",
    new SelectList(Model.Titles, "Key", "Value"))%>

This will render:

<select id="Contact_Title" name="Contact.Title">...

It only replaces the dot in the id as it's not valid in xhtml.

Mattias Jakobsson
That cannot be the case as on any standard item, like Html.TextBoxFor it DOES include a dot in the name attribute (check the examples in my question).
Sohnee
It will include a dot in the name attribute (that is valid), but not in the id attribute (that is invalid). And it's the same for all helpers.
Mattias Jakobsson
Cool - this works too and saves extra code. Thanks Mattias.
Sohnee