Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get id of element for JavaScript in MVC4/Razor from nested object in model

If I define a textbox like this:

@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 would still have to hardcode _ to concatenate Contact and HomePhone.)

like image 920
vlscanner Avatar asked Oct 10 '13 03:10

vlscanner


People also ask

How do you give ID in Razor syntax?

Just add the id property to the html-attributes. That will override the default id generated by the editorfor-helper-methode. Save this answer.

Can I use Razor code in JavaScript in ASP.NET MVC?

Solution 1. You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser.

What is razor view in MVC with example?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.

Does MVC use razor?

Razor is one of the view engines supported in ASP.NET MVC. Razor allows you to write a mix of HTML and server-side code using C# or Visual Basic.


1 Answers

Try this way, using Html.IdFor you can get the id generated by the helper.

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

Just prefix it with # for jquery to pick it up.

But you can also bind the plugin using class selector, say for example if you have many such phone fields you can provide a common class to all those textBoxes and bind mask plugin to it using the class selector, this would avoid determining 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 the id you can just bind them.

 $('.phoneField').mask("(999) 999-9999");
like image 154
PSL Avatar answered Sep 20 '22 09:09

PSL