asp.net mvc 使用Htmlhelper类向前台输出自定义方法

HtmlHelper类中支持向前台输出标签的功能。但是我们有时候需要添加一些属性。所以,这样的方法诞生了。 
/// <summary>
    /// Returns a text input element for each property in the object that is represented by the specified expression, using the specified HTML attributes.
    /// </summary>
    ///
    /// <returns>
    /// An HTML input element whose type attribute is set to "text" for each property in the object that is represented by the expression.
    /// </returns>
    /// <param name="htmlHelper">The HTML helper instance that this method extends.</param><param name="expression">An expression that identifies the object that contains the properties to render.</param><param name="htmlAttributes">An object that contains the HTML attributes to set for the element.</param><typeparam name="TModel">The type of the model.</typeparam><typeparam name="TProperty">The type of the value.</typeparam><exception cref="T:System.ArgumentException">The <paramref name="expression"/> parameter is null or empty.</exception>
    public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
      return InputExtensions.TextBoxFor<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>) HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }
就拿它来举例说明一下,这是一个拓展方法相信大家都知道,(对于不知知道的就去百度下很简单的)。
使用最后面的参数便是定义添加属性的参数。
 例如:
    @Html.TextBoxFor(m=>m.ValiateCodeP,new{sb="aaa",@class="login-text"})
后面第二个参数直接跟匿名对象即可,但是注意一点看到我的第二个参数出现了class标记了,这在.net平台代码中这是关键字是不能使用的,那么要怎么办,就想我的例子中在前面加@标记取消关键字就可以了。

posted on 2016-03-16 10:46  forgive-me  阅读(92)  评论(0编辑  收藏  举报

导航