How to control the html element id and name when using MVC2's EditorFor helper
I'm curently refactoring my MVC2 code base to use the ViewModel approach versus. As a result, the models I'm =passing to my views to render forms now look like
model.TheObject
model.TheCollectionOfOtherObjects
I'm trying to use the HTML.EditorFor helper to render a Template Editor for a data type. It used to work when I was trying to render TheObject directly in the view, now that there's a level of indirection, I'm getting a totally different default object naming scheme:
For example:
Before I did the refactoring into the ViewModel, I output a special JQuery based date picker:
<%: Html.EditorFor(model => model.StartDate, String.Format("{0:M/d/yyyy}", Model.StartDate))%>
Output:
<input id="StartDate" name="StartDate" type="text" value="7/5/2010 11:10:25 AM" />
All was happy in JQuery land.
Then I changed the view to use a ViewModel that contained TheObject and changed my EditorFor code to the following:
<%: Html.EditorFor(model => model.TheObject.StartDate, String.Format("{0:M/d/yyyy}", Model.TheObject.StartDate))%>
Now renders the following HTML:
<input id="TheObject_StartDate" name="TheObject开发者_运维百科.StartDate" type="text" value="7/5/2010 11:10:25 AM" />
This, naturally breaks my JQuery on the client side, and I'd prefer to have more control over output the id and name attributes on the html element.
Any ideas on how I change that lamba expression that I pass into EditorFor
Thanks
Why not just use CSS selectors instead, or match the ID but look at the end like $("input[id$='StartDate']")?
There is only so much you can control with this approach; could just use Html.TextBox and not use the For syntax. That gives you complete control...
The TextBoxFor approach, with the ID it gives, ensures that any posts to the server can recreate the model trail of the same object type...
HTH.
Bit late, but for the benefit of others there is the Html.IdFor() that would allow you to get the generated ID. You could then write that into the JavaScript for JQuery to use.
<%: Html.IdFor(model => model.TheObject.StartDate) %>
精彩评论