How can I retrieve element Id for Strolngly typed ASP.NET MVC HTML helper? [duplicate]
Possible Duplicate:
Client Id for Property (ASP.Net MVC)
In my View I'm using jquery ui datapicker. So I need initiate 开发者_StackOverflow中文版it with code like this
$(function() {
$('#elementID').datepicker({
});
});
In my View
<%= Html.TextBoxFor(m=>m.StartDate) %>
In old ASP.NET I may use
tb_startDate.ClientID
What is about retrieving element Id of Strongly Typed ASP.NET MVC HTML Helper? Is is possible?
There is no way of receiving the id of the textbox once it has been rendered (as it just outputs plain text).
You can, however use another approach where you set the class and use a standard ".class-jquery selector".
Like so:
<%= Html.TextBoxFor(m=>m.StartDate, new { @class = "startDate" }) %>
and:
$('input.startDate').datepicker();
You can create
public static class HtmlExtensions
{
public static MvcHtmlString FieldIdFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string inputFieldId = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName);
return MvcHtmlString.Create(inputFieldId);
}
}
and used used it
$('@Html.FieldIdFor(m=>m.StartDate').datepicker();
For more details: http://www.dominicpettifer.co.uk/Blog/37/strongly-typed--label--elements-in-asp-net-mvc-2
精彩评论