MVC中,获取TextBoxFor生成的ID,Name

在MVC中,写EditorTemplates,为某些数据类型(如:DateTime)提供更丰富的客户端表现。

在模板中可以用

@Html.TextBoxFor(x => x)

的形式生成一个文本框。

 

之后,如要使用jquery等对此文本框操作,会遇到一个问题,不知道这个文本框的id是什么研究mvc源码发现,可以用

@Html.ViewData.TemplateInfo.GetFullHtmlFieldId("")

来获得

空字符串意味着model本身,而不是model的某个属性,如果是属性,需要传属性名

可以用MVC提供的

ExpressionHelper.GetExpressionText

方法获得

  1: public static string GetExpressionText<TModel,TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel,TProperty>> expression)
  2: {
  3:     return ExpressionHelper.GetExpressionText(expression);
  4: }
  1: public static string GetHtmlFieldFullID<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
  2: {
  3:     return helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(helper.GetExpressionText(expression));
  4: }
  1: public static string GetHtmlFieldFullName<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
  2: {
  3:     return helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(helper.GetExpressionText(expression));
  4: }

调用扩展方法

@Html.GetHtmlFieldFullID(x=>x)
 
mvc源码
Mvc\Html\InputExtensions.cs
image 
image 
原文地址:https://www.cnblogs.com/czcz1024/p/2203945.html