Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the generated clientid for a form field

Tags:

asp.net-mvc

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>
like image 667
Jokin Avatar asked Mar 24 '11 12:03

Jokin


3 Answers

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)

like image 195
John Landheer Avatar answered Nov 06 '22 03:11

John Landheer


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.

like image 26
Theophilus Avatar answered Nov 06 '22 01:11

Theophilus


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

like image 9
Professor of programming Avatar answered Nov 06 '22 01:11

Professor of programming