Is there a way to get the client id generated for a field generated with a html helper?
i have several components that sometimes are inside another forms, and i wan't to attach javascript events to them.
so, for sample, i would like to have:
@Html.TextBoxFor(model => model.client.email)
<script>
$('#@getmyusercontrolid(model=>model.client.email)').val("put your mail here");
</script>
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)
MVC 5 has NameFor, so your example using it is:
@Html.TextBoxFor(model => model.client.email)
<script>
$('#@Html.NameFor(model => model.client.email)').val("put your mail here");
</script>
EDIT
IdFor is also available, which may be more appropriate in this situation than NameFor
.
Use @Html.IdFor(model => model.client.email)
as this functionality already exists like so:
@Html.TextBoxFor(model => model.client.email)
<script>
$('#@Html.IdFor(model => model.client.email)').val("put your mail here");
</script>
You can read more about it at the following page: https://msdn.microsoft.com/en-us/library/hh833709%28v=vs.118%29.aspx
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