最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Get id of element for JavaScript in MVC4Razor from nested object in model - Stack Overflow

programmeradmin3浏览0评论

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.)

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.)

Share Improve this question edited Oct 25, 2013 at 2:06 michaelb958--GoFundMonica 4,7087 gold badges33 silver badges35 bronze badges asked Oct 10, 2013 at 3:34 vlscannervlscanner 4581 gold badge5 silver badges16 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 21

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");
发布评论

评论列表(0)

  1. 暂无评论