get the generated clientid for a form field
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 ha开发者_如何学运维ve:
@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
You could try specifying the id in the HtmlAttributes argument when you generate the input field, e.g.
@Html.TextBoxFor(model => model.client.email, new { id = "emailTextBox" })
Then you can use this in your javaScript
var email = $('#emailTextBox').val();
精彩评论