Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the HTML id generated by asp.net MVC EditorFor

I use the HTML Helpers to render my fields:

<%=Html.EditorFor(m => m.User.Surname)%> 

and the output would be something like this:

<input class="text-box single-line" id="User_Surname"            name="User.Surname" type="text" value="" /> 

The helper uses the className + '.' è fieldName to build the id.
I need to pass the id to a jQuery function. Is there a way to have it without hardcoding it? Maybe an helper which can use the ASP.NET MVC2 conventions?

like image 434
LeftyX Avatar asked Jan 28 '11 14:01

LeftyX


People also ask

What is HTML EditorFor in MVC?

ASP.NET MVC includes the method that generates HTML input elements based on the datatype. The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.

What is the difference between HTML textbox HTML TextBoxFor and HTML EditorFor?

Show activity on this post. TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control. EditorFor: This control is bit smart.

How does HTML EditorFor work?

Simply put, the Html. EditorFor method allows the developer to retain control over the display of form elements by data type (ie. string, boolean, int…etc) or model attribute at a global level rather than at an individual view level. This allows for cleaner ASP markup and easily scalable form controls.

What does HTML helper class generate?

The HtmlHelper class generates HTML elements. For example, @Html. ActionLink("Create New", "Create") would generate anchor tag <a href="/Student/Create">Create New</a> . There are many extension methods for HtmlHelper class, which creates different HTML controls.


2 Answers

ASP.NET MVC 4 has Html.IdFor() built in that can return this:

@Html.IdFor(m => m.User.Surname) 
like image 111
bkaid Avatar answered Oct 13 '22 19:10

bkaid


See this question: get the generated clientid for a form field, this is my answer:

I use this helper:

public static partial class HtmlExtensions {     public static MvcHtmlString ClientIdFor<TModel, TProperty>(         this HtmlHelper<TModel> htmlHelper,          Expression<Func<TModel, TProperty>> expression)     {         return MvcHtmlString.Create(               htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(                   ExpressionHelper.GetExpressionText(expression)));     } } 

Use it just as you would any other helper: @Html.ClientIdFor(model=>model.client.email)

like image 23
John Landheer Avatar answered Oct 13 '22 18:10

John Landheer