how to create an HTML Helper to Extend TextBoxFor() to add CSS style?
@Html.TextBoxFor(model => model.FirstName, new { @class = \"txt\" })
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);
}