Reputation: 23
I try to create a custom textbox in mvc. I want to add default class value "text-uppercase".I also want add new class values in view.
Myhelper class is;
public static MvcHtmlString Custom_TextBox<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
{
ModelMetadata oModelMetadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
if (htmlAttributes == null)
{
htmlAttributes = new Dictionary<string, object>();
}
htmlAttributes.Add("type", "text");
htmlAttributes.Add("name", oModelMetadata.DisplayName);
htmlAttributes.Add("id", oModelMetadata.DisplayName);
htmlAttributes.Add("class", "text-uppercase");
return helper.TextBoxFor(expression, htmlAttributes);
}
And my view code:
@Html.Custom_TextBox(model => model.YazilimAdi,new { @class = "form-control" } )
Actually the error is: An item with the same key has already been added. "class".
How can i add my default class value "text-uppercase"?
Upvotes: 0
Views: 309
Reputation: 3744
if(htmlAttributes.ContainsKey("class"))
{
htmlAttributes["class"] += " text-uppercase";
}
else
{
htmlAttributes.Add("class", "text-uppercase");
}
and put this at the beginning of extension:
if (htmlAttributes == null)
{
htmlAttributes = new Dictionary<string, object>();
}
Upvotes: 2