Get the identifier of a JavaScript element in MVC4 / Razor from a nested object in the model

If I define the text box as follows:

@Html.TextBoxFor(m => m.Contact.HomePhone) 

it will generate an input element with id Contact_HomePhone .

Is it possible to get this id in JavaScript without hardcoding Contact_HomePhone ?

This is an example of where I need this id dynamically in JavaScript:

 $("#Contact_HomePhone").mask("(999) 999-9999"); 

(I know how to get property names using reflection, but you still have to hardcode _ to combine Contact and HomePhone .)

+8
javascript c # asp.net-mvc razor asp.net-mvc-4
source share
1 answer

Try this method using Html.IdFor , you can get the identifier created by the helper.

 $('#@Html.IdFor(m => m.Contact.HomePhone)').mask("(999) 999-9999"); 

Just a c # prefix for jquery to pick it up.

But you can also bind the plugin using the class selector, for example, if you have many such telephone fields, you can provide a common class to all these text fields and connect the mask plugin to it using the class selector, this will avoid identifying the id using the above method and use a common selector.

  @Html.TextBoxFor(m => m.Contact.HomePhone, null, new { @class = "phoneField"}); 

and without worrying about id, you can just bind them.

  $('.phoneField').mask("(999) 999-9999"); 
+14
source share

All Articles