how to create an HTML Helper to Extend TextBoxFor() to add CSS style?

前端 未结 3 864
醉话见心
醉话见心 2020-12-10 14:11

how to create an HTML Helper to Extend TextBoxFor() to add CSS style?

@Html.TextBoxFor(model => model.FirstName, new { @class = \"txt\" }) 
3条回答
  •  情话喂你
    2020-12-10 15:02

    Building on answer by @nemesv, here is an extension that supports htmlAttributes with additional custom attributes.

    vb.net:

    
    Function MyTextBoxFor(Of TModel, TProperty)(ByVal helper As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of TModel, TProperty)), htmlAttributes As Object) As MvcHtmlString           
        'copy htmlAttributes object to Dictionary
        Dim dicHtmlAttributes As New Dictionary(Of String, Object)
        For Each prop in htmlAttributes.GetType().GetProperties()
            dicHtmlAttributes.Add(prop.Name,prop.GetValue(htmlAttributes))
        Next
        'add custom attribute
        dicHtmlAttributes.Add("foo","bar")
    
        Return helper.TextBoxFor(expression, dicHtmlAttributes)
    End Function
    

    c#:

    public static MvcHtmlString MyTextBoxFor(
         this HtmlHelper helper, 
         Expression> expression, object htmlAttributes)
    {
        // copy htmlAttributes object to Dictionary
        Dictionary dicHtmlAttributes = new Dictionary();
        foreach (var prop in htmlAttributes.GetType().GetProperties())
        {
            dicHtmlAttributes.Add(prop.Name, prop.GetValue(htmlAttributes));
        }
        //add custom attribute
        dicHtmlAttributes.Add("foo", "bar");
        return helper.TextBoxFor(expression, dicHtmlAttributes);
    }
    

提交回复
热议问题