I created a custom HTMLHelper extension method for Razor
public static MvcHtmlString BootstrapButtonGroupForEnum<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
// render stuff
}
And use it like this:
@Html.BootstrapButtonGroupForEnum(model => model.PriceType)
It works fine for adding records, but how to I pass the value of the model's method to it? So I can make a value preselected. Do I need to pass the value via an additional parameter or is there a more elegant way of doing this. I had a look in Watch and did not see the value there, did I miss something?
Thanks!
EDIT: The full implementation of the html helper:
public static MvcHtmlString BootstrapButtonGroupForEnum<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string[] listOfNames = Enum.GetNames(metaData.ModelType);
var sb = new StringBuilder();
if (listOfNames != null)
{
sb = sb.Append("<div class=\"btn-group btn-group\" role=\"group\" >");
foreach (var value in listOfNames)
{
sb.Append("<button type=\"button\" class=\"btn btn-primary\" onclick=\"");
// onclick event hadler
sb.AppendFormat("$('#{0}').val('{1}');", metaData.PropertyName, value); // get the value to the hidden
sb.Append("$(this).addClass('active').siblings().removeClass('active');"); // retain selection
sb.Append("\">");
sb.Append(value.ToString().UnPascalCase());
sb.Append("</button>");
}
sb = sb.Append("</div>");
sb = sb.AppendFormat("<input type=\"hidden\" id=\"{0}\" name=\"{0}\" />", metaData.PropertyName);
}
return MvcHtmlString.Create(sb.ToString());
}
I suppose I could try using @HiddenFor(...) instead of rendering it directly as html?