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?
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.
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.
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.
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.
ASP.NET MVC 4 has Html.IdFor() built in that can return this:
@Html.IdFor(m => m.User.Surname)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With