How to Use check box list in MVC - asp.net-mvc

I need to display check box list with more than one options. User must select minimum one check box, user can select more than one check boxes.
I want to store values of all check boxes (selected) in one field as a string(Data base) with coma separated. This is not mandatory, mandatory is need to store multiple values of each selected check box. Alternate solutions are welcome.
Model
public class Member
{
public string Member_VehicalType { get; set; }
public IList<SelectListItem> Member_VehicalType_List { get; set; }
Controller
[HttpGet]
public ActionResult Create()
{
Member objMemberModel = new Member();
List<SelectListItem> vehical_Types = new List<SelectListItem>();
vehical_Types.Add(new SelectListItem { Text = "Two Wheeler", Value = "1" });
vehical_Types.Add(new SelectListItem { Text = "Four Wheeler", Value = "2" });
objMemberModel.Member_VehicalType_List = vehical_Types;
return View(objMemberModel);
How do I create view with #Html.CheckBoxFor( or #Html.CheckBox(

I recently had to deal with SelectListItem as a checkbox-list. I came up with the following HtmlExtensions, which might be helpful. These extensions provide the same functionality as the #Html.DropDownListFor(model => ...);
Usage: #Html.CheckBoxListFor(model => model.ModelMemberToPutValueIn, Model.Member_VehicalType_List)
public static class HtmlExtensions
{
public static MvcHtmlString CheckBoxListFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, IEnumerable<SelectListItem> items, object htmlAttributes = null)
{
var listName = ExpressionHelper.GetExpressionText(expression);
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
items = GetCheckboxListWithDefaultValues(metaData.Model, items);
return htmlHelper.CheckBoxList(listName, items, htmlAttributes);
}
public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string listName, IEnumerable<SelectListItem> items, object htmlAttributes = null)
{
if (items == null) return null;
var container = new TagBuilder("div");
container.AddCssClass("checkbox-list");
container.MergeAttribute("id", HtmlHelper.GenerateIdFromName(listName));
foreach (var item in items)
{
var id = HtmlHelper.GenerateIdFromName(String.Join(".", listName, item.Text));
var div = new TagBuilder("div");
div.AddCssClass("checkbox");
var cb = new TagBuilder("input");
cb.MergeAttribute("type", "checkbox");
cb.MergeAttribute("id", id);
cb.MergeAttribute("name", listName);
cb.MergeAttribute("value", item.Value ?? item.Text);
if (item.Selected) cb.MergeAttribute("checked", "checked");
var label = new TagBuilder("label");
label.MergeAttribute("for", id);
label.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
label.InnerHtml = item.Text;
div.InnerHtml = cb.ToString(TagRenderMode.SelfClosing) + label;
container.InnerHtml += div;
}
return new MvcHtmlString(container.ToString());
}
private static IEnumerable<SelectListItem> GetCheckboxListWithDefaultValues(object defaultValues, IEnumerable<SelectListItem> selectList)
{
var defaultValuesList = defaultValues as IEnumerable;
if (defaultValuesList == null) return selectList;
var values = from object value in defaultValuesList select Convert.ToString(value, CultureInfo.CurrentCulture);
var selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);
var newSelectList = new List<SelectListItem>();
foreach (var item in selectList)
{
item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);
newSelectList.Add(item);
}
return newSelectList;
}
}

Related

Custom DropDownListFor Helper loads an empty value for the selected element

I am using a custom helper, to create a select element that can take HtmlAttribute. I am using the same code as I found here, in #Alexander Puchkov answer (which I'll post for reference).
It's working fine, apart when the DDL helper is loaded with one of the option as the selected item, then the value of the selected item is null/empty. (i.e. on an edit page the DDL loads up with the option that was set on creation, rather than the '-Please select option-'),
The highlighted attribute in the picture shows the problem, the value should not be empty, but should show 'Medium'...
So the text is display correctly but the element has no value. Any ideas on where this issue comes from?
Here is the full code of the helper:
/// <summary>
/// A selectListItem with an extra property to hold HtmlAttributes
/// <para>Used in conjunction with the sdDDL Helpers</para>
/// </summary>
public class SdSelectListItem : SelectListItem
{
public object HtmlAttributes { get; set; }
}
/// <summary>
/// Generate DropDownLists with the possibility of styling the 'option' tags of the generated 'select' tag
/// </summary>
public static class SdDdlHelper
{
public static MvcHtmlString sdDDLFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, IEnumerable<SdSelectListItem> selectList,
string optionLabel, object htmlAttributes)
{
if (expression == null)
throw new ArgumentNullException("expression");
ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
return SelectInternal(htmlHelper, metadata, optionLabel, ExpressionHelper.GetExpressionText(expression), selectList,
false /* allowMultiple */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString sdDDLFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, IEnumerable<SdSelectListItem> selectList,
object htmlAttributes)
{
if (expression == null)
throw new ArgumentNullException("expression");
ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
//-> The below line is my problem (specifically the 'null' param), it set to null if no option label is passed to the method...So if I use this overload, the DDL will load (or re-load) with the default value selected, not the value binded to the property - And if I use the above overload, and set Model.action_priority as the optionLabel, then I get what is shown in the picture...
return SelectInternal(htmlHelper, metadata, null, ExpressionHelper.GetExpressionText(expression), selectList,
false /* allowMultiple */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
#region internal/private methods
private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata, string optionLabel, string name,
IEnumerable<SdSelectListItem> selectList, bool allowMultiple,
IDictionary<string, object> htmlAttributes)
{
string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
if (String.IsNullOrEmpty(fullName))
throw new ArgumentException("No name");
if (selectList == null)
throw new ArgumentException("No selectlist");
object defaultValue = (allowMultiple)
? htmlHelper.GetModelStateValue(fullName, typeof(string[]))
: htmlHelper.GetModelStateValue(fullName, typeof(string));
// If we haven't already used ViewData to get the entire list of items then we need to
// use the ViewData-supplied value before using the parameter-supplied value.
if (defaultValue == null)
defaultValue = htmlHelper.ViewData.Eval(fullName);
if (defaultValue != null)
{
IEnumerable defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue };
IEnumerable<string> values = from object value in defaultValues
select Convert.ToString(value, CultureInfo.CurrentCulture);
HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);
List<SdSelectListItem> newSelectList = new List<SdSelectListItem>();
foreach (SdSelectListItem item in selectList)
{
item.Selected = (item.Value != null)
? selectedValues.Contains(item.Value)
: selectedValues.Contains(item.Text);
newSelectList.Add(item);
}
selectList = newSelectList;
}
// Convert each ListItem to an <option> tag
StringBuilder listItemBuilder = new StringBuilder();
// Make optionLabel the first item that gets rendered.
if (optionLabel != null)
listItemBuilder.Append(
ListItemToOption(new SdSelectListItem()
{
Text = optionLabel,
Value = String.Empty,
Selected = false
}));
foreach (SdSelectListItem item in selectList)
{
listItemBuilder.Append(ListItemToOption(item));
}
TagBuilder tagBuilder = new TagBuilder("select")
{
InnerHtml = listItemBuilder.ToString()
};
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("name", fullName, true /* replaceExisting */);
tagBuilder.GenerateId(fullName);
if (allowMultiple)
tagBuilder.MergeAttribute("multiple", "multiple");
// If there are any errors for a named field, we add the css attribute.
System.Web.Mvc.ModelState modelState;
if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState))
{
if (modelState.Errors.Count > 0)
{
tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
}
}
tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(fullName, metadata));
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
internal static string ListItemToOption(SdSelectListItem item)
{
TagBuilder builder = new TagBuilder("option")
{
InnerHtml = HttpUtility.HtmlEncode(item.Text)
};
if (item.Value != null)
{
builder.Attributes["value"] = item.Value;
}
if (item.Selected)
{
builder.Attributes["selected"] = "selected";
}
builder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(item.HtmlAttributes));
return builder.ToString(TagRenderMode.Normal);
}
internal static object GetModelStateValue(this HtmlHelper htmlHelper, string key, Type destinationType)
{
System.Web.Mvc.ModelState modelState;
if (htmlHelper.ViewData.ModelState.TryGetValue(key, out modelState))
{
if (modelState.Value != null)
{
return modelState.Value.ConvertTo(destinationType, null /* culture */);
}
}
return null;
}
#endregion
}
}
Here is how I call it in the View (using Razor):
#Html.sdDDLFor(x => Model.action_priority, Model.actionPriorityDDL(), Model.action_priority, new
{
#id = "_Action_Priority_DDL",
#class = "form-control"
})
And finally here is the Model.actionPriorityDDL() method:
public List<SdSelectListItem> actionPriorityDDL()
{
action_priority_DDL = new List<SdSelectListItem>();
action_priority_DDL.Add(new SdSelectListItem
{
Value = StringRepository.ActionPriority.high,
Text = StringRepository.ActionPriority.high,
HtmlAttributes = new
{
#class = "lbl-action-priority-high"
}
}
);
action_priority_DDL.Add(new SdSelectListItem
{
Value = StringRepository.ActionPriority.medium,
Text = StringRepository.ActionPriority.medium,
HtmlAttributes = new
{
#class = "lbl-action-priority-medium"
}
}
);
action_priority_DDL.Add(new SdSelectListItem
{
Value = StringRepository.ActionPriority.low,
Text = StringRepository.ActionPriority.low,
HtmlAttributes = new
{
#class = "lbl-action-priority-low"
}
}
);
action_priority_DDL.Add(new SdSelectListItem
{
Value = StringRepository.ActionPriority.psar,
Text = StringRepository.ActionPriority.psar,
HtmlAttributes = new
{
#class = "lbl-action-priority-psar"
}
}
);
return action_priority_DDL;
}
This is caused by a former bug in MVC framework (http://aspnet.codeplex.com/workitem/8311; accessible here: https://web.archive.org/web/20131208041521/http://aspnet.codeplex.com/workitem/8311) that happens when using the DropDownListFor helper within a loop, i.e. the model property has an indexer (like in your example, where the generated select element has an attribute name="actionList[0].action_priority")
I resolved this by copying some code from here https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/Html/SelectExtensions.cs
Specifically, in this method
private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata, string optionLabel, string name,
IEnumerable<ExtendedSelectListItem> selectList, bool allowMultiple,
IDictionary<string, object> htmlAttributes)
replace this
if (selectList == null)
throw new ArgumentException("No selectlist");
with:
bool usedViewData = false;
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = htmlHelper.GetSelectData(name);
usedViewData = true;
}
Now, replace this
if (defaultValue == null)
defaultValue = htmlHelper.ViewData.Eval(fullName);
with:
if (defaultValue == null && !String.IsNullOrEmpty(name))
{
if (!usedViewData)
{
defaultValue = htmlHelper.ViewData.Eval(name);
}
else if (metadata != null)
{
defaultValue = metadata.Model;
}
}
Finally, you also need to add this method:
private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
{
object o = null;
if (htmlHelper.ViewData != null)
{
o = htmlHelper.ViewData.Eval(name);
}
if (o == null)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
MvcResources.HtmlHelper_MissingSelectData,
name,
"IEnumerable<SelectListItem>"));
}
IEnumerable<SelectListItem> selectList = o as IEnumerable<SelectListItem>;
if (selectList == null)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
MvcResources.HtmlHelper_WrongSelectDataType,
name,
o.GetType().FullName,
"IEnumerable<SelectListItem>"));
}
return selectList;
}
replacing SelectListItem with your custom class (e.g. SdSelectListItem, or ExtendedSelectListItem , or whatever you named it )

Optgroup in DropDownlistFor MVC 4 Not Support Mvc validation

public static MvcHtmlString DropDownGroupListFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, IEnumerable<GroupedSelectListItem> selectList, string defaultText, object htmlAttributes, bool isDisabled)
{
if (isDisabled)
{
IDictionary<string, object> htmlAttributeMerge = new RouteValueDictionary(htmlAttributes);
htmlAttributeMerge.Add("disabled", "disabled");
return DropDownGroupListFor(htmlHelper,expression, selectList, defaultText, htmlAttributeMerge);
}
else
{
return DropDownGroupListFor(htmlHelper, expression, selectList, defaultText, htmlAttributes);
}
}
// Helper methods
private static IEnumerable<GroupedSelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
{
object o = null;
if (htmlHelper.ViewData != null)
{
o = htmlHelper.ViewData.Eval(name);
}
if (o == null)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"Missing Select Data",
name,
"IEnumerable<GroupedSelectListItem>"));
}
IEnumerable<GroupedSelectListItem> selectList = o as IEnumerable<GroupedSelectListItem>;
if (selectList == null)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"Wrong Select DataType",
name,
o.GetType().FullName,
"IEnumerable<GroupedSelectListItem>"));
}
return selectList;
}
internal static string ListItemToOption(GroupedSelectListItem item)
{
TagBuilder builder = new TagBuilder("option")
{
InnerHtml = HttpUtility.HtmlEncode(item.Text)
};
if (item.Value != null)
{
builder.Attributes["value"] = item.Value;
}
if (item.Selected)
{
builder.Attributes["selected"] = "selected";
}
return builder.ToString(TagRenderMode.Normal);
}
private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, string optionLabel, string name, IEnumerable<GroupedSelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes)
{
name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
if (String.IsNullOrEmpty(name))
{
throw new ArgumentException("Null Or Empty", "name");
}
bool usedViewData = false;
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = GetSelectData(htmlHelper, name);
usedViewData = true;
}
object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(name, typeof(string[])) : htmlHelper.GetModelStateValue(name, typeof(string));
// If we haven't already used ViewData to get the entire list of items then we need to
// use the ViewData-supplied value before using the parameter-supplied value.
if (!usedViewData)
{
if (defaultValue == null)
{
defaultValue = htmlHelper.ViewData.Eval(name);
}
}
if (defaultValue != null)
{
IEnumerable defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue };
IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture);
HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);
List<GroupedSelectListItem> newSelectList = new List<GroupedSelectListItem>();
foreach (GroupedSelectListItem item in selectList)
{
item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);
newSelectList.Add(item);
}
selectList = newSelectList;
}
// Convert each ListItem to an <option> tag
StringBuilder listItemBuilder = new StringBuilder();
// Make optionLabel the first item that gets rendered.
if (optionLabel != null)
{
listItemBuilder.AppendLine(ListItemToOption(new GroupedSelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false }));
}
foreach (var group in selectList.GroupBy(i => i.GroupKey))
{
string groupName = selectList.Where(i => i.GroupKey == group.Key).Select(it => it.GroupName).FirstOrDefault();
listItemBuilder.AppendLine(string.Format("<optgroup label=\"{0}\" value=\"{1}\">", groupName, group.Key));
foreach (GroupedSelectListItem item in group)
{
listItemBuilder.AppendLine(ListItemToOption(item));
}
listItemBuilder.AppendLine("</optgroup>");
}
TagBuilder tagBuilder = new TagBuilder("select")
{
InnerHtml = listItemBuilder.ToString()
};
foreach (var htmlAttribute in htmlAttributes)
{
tagBuilder.MergeAttribute(
htmlAttribute.Key.Replace('_', '-'),
(string)htmlAttribute.Value
);
}
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("name", name, true /* replaceExisting */);
tagBuilder.GenerateId(name);
if (allowMultiple)
{
tagBuilder.MergeAttribute("multiple", "multiple");
}
// If there are any errors for a named field, we add the css attribute.
ModelState modelState;
if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState))
{
if (modelState.Errors.Count > 0)
{
tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
}
}
return MvcHtmlString.Create(tagBuilder.ToString());
}
internal static object GetModelStateValue(this HtmlHelper helper, string key, Type destinationType)
{
ModelState modelState;
if (helper.ViewData.ModelState.TryGetValue(key, out modelState))
{
if (modelState.Value != null)
{
return modelState.Value.ConvertTo(destinationType, null /* culture */);
}
}
return null;
}
#Html.DropDownGroupListFor(m => m.id, Model.list, null, new { #class
= "form-control"})
this the whole code Validation On Id But validtion not work,validation is server side when click on button to submit validtion not fire why?

DropDownListFor for enum with custom values (stored in attributes) doesn't select item

I have enum with assigned string values (in attributes) and would like to have html helper for displaying it. Unfortunately I need to use assigned values as a keys in ddl. Because of that it doesn't select item stored in ViewModel. What to do?
Sample Enum
public enum StatusEnum
{
[Value("AA")]
Active,
[Value("BB")]
Disabled
}
ViewModel
public class UserViewModel
{
public StatusEnum Status { get; set; }
}
View
#Html.DropDownListForEnum(x => x.Status, new {})
DropDownListForEnum helper
public static MvcHtmlString DropDownListForEnum<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
IEnumerable<SelectListItem> items = Enum.GetNames(typeof(TEnum))
.Select(n => (TEnum)Enum.Parse(typeof(TEnum), n))
.Select(e => new SelectListItem() {
Text = e.ToString(),
Value = EnumExtension.GetValue(e).ToString(),
Selected = EnumExtension.GetValue(e) == EnumExtension.GetValue(metadata.Model)
})
.ToList();
return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}
Instead of passing IEnumerable<SelectListItem> to the dropdown, create and populate SelectList manually and pass that and it will work:
public static MvcHtmlString DropDownListForEnum<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var items = Enum.GetNames(typeof(TEnum))
.Select(n => (TEnum)Enum.Parse(typeof(TEnum), n))
.Select(e => new
{
Id = Convert.ToInt32(e),
Text = e.ToString(),
Value = EnumExtension.GetValue(e).ToString(),
Selected = EnumExtension.GetValue(e) == EnumExtension.GetValue(metadata.Model)
})
.ToList();
var selectList = new SelectList(items, "Text", "Value", selectedValue: items.Find(i => i.Selected).Text);
return htmlHelper.DropDownListFor(expression, selectList, htmlAttributes);
}

Generic Checkbox List View model in MVC

I want to create a generic checkbox list view model and so I got this:
public class ChckboxListViewModel<T>
{
public List<CheckboxViewModel<T>> CheckboxList { get; set; }
public IEnumerable<T> SelectedValues
{
get { return CheckboxList.Where(c => c.IsSelected).Select(c => c.Value); }
}
public ChckboxListViewModel()
{
CheckboxList = new List<CheckboxViewModel<T>>();
}
}
public class CheckboxViewModel<T>
{
public string Label { get; set; }
public T Value { get; set; }
public bool IsSelected { get; set; }
public CheckboxViewModel(string i_Label, T i_Value, bool i_IsSelected)
{
Label = i_Label;
Value = i_Value;
IsSelected = i_IsSelected;
}
}
It is used by a different view model to represent filters of different statuses:
public class FaultListFilters
{
public string SearchKeyword { get; set; }
public ChckboxListViewModel<Fault.eFaultStatus> StatusFilter { get; set; }
public FaultListFilters()
{
SearchKeyword = null;
StatusFilter = new ChckboxListViewModel<Fault.eFaultStatus>();
StatusFilter.CheckboxList.Add(new CheckboxViewModel<Fault.eFaultStatus>(FaultManagementStrings.OpenStatus,Fault.eFaultStatus.Open,true));
StatusFilter.CheckboxList.Add(new CheckboxViewModel<Fault.eFaultStatus>(FaultManagementStrings.InProgressStatus, Fault.eFaultStatus.InProgress, true));
StatusFilter.CheckboxList.Add(new CheckboxViewModel<Fault.eFaultStatus>(FaultManagementStrings.ClosedStatus, Fault.eFaultStatus.Close, false));
}
}
Now I can't find the right way to display the editors or to create an editor template for that kind of a view model because it is Generic.
I don't want o create a separate editor template for ChckboxListViewModel<int> and then another for ChckboxListViewModel<Fault.eFaultStatus> and so on..
Is it even a goose idea to use generics in this case?
Is there another way to represent and display a check-box list in MVC?
I have done the following but the modle is not binding for some reason:
#using (Html.BeginForm("FaultManagement", "Faults", FormMethod.Get, null))
{
for (int i=0 ; i<Model.FaultListFilters.StatusFilter.CheckboxList.Count() ; i++)
{
#Html.HiddenFor(m => m.FaultListFilters.StatusFilter.CheckboxList[i].Value)
#Html.CheckBoxFor(m => m.FaultListFilters.StatusFilter.CheckboxList[i].IsSelected)
#Html.LabelFor(m=> m.FaultListFilters.StatusFilter.CheckboxList[i].IsSelected,Model.FaultListFilters.StatusFilter.CheckboxList[i].Label)
}
<input type="submit" />
}
Is it even a goose idea to use generics in this case?
Don't think it is.
Is there another way to represent and display a check-box list in MVC?
I would write a custom HTML helper:
public static class HtmlExtensions
{
public static IHtmlString CheckboxListFor<TModel>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, IEnumerable<string>>> ex,
IEnumerable<string> possibleValues)
{
var metadata = ModelMetadata.FromLambdaExpression(ex, html.ViewData);
var availableValues = (IEnumerable<string>)metadata.Model;
var name = ExpressionHelper.GetExpressionText(ex);
return html.CheckboxList(name, availableValues, possibleValues);
}
private static IHtmlString CheckboxList(this HtmlHelper html, string name, IEnumerable<string> selectedValues, IEnumerable<string> possibleValues)
{
var result = new StringBuilder();
foreach (string current in possibleValues)
{
var label = new TagBuilder("label");
var sb = new StringBuilder();
var checkbox = new TagBuilder("input");
checkbox.Attributes["type"] = "checkbox";
checkbox.Attributes["name"] = name;
checkbox.Attributes["value"] = current;
var isChecked = selectedValues.Contains(current);
if (isChecked)
{
checkbox.Attributes["checked"] = "checked";
}
sb.Append(checkbox.ToString());
sb.Append(current);
label.InnerHtml = sb.ToString();
result.Append(label);
}
return new HtmlString(result.ToString());
}
}
Then you could have a view model:
public class FaultListFiltersViewModel
{
public IEnumerable<string> SelectedStatusFilters { get; set; }
public IEnumerable<string> AvailableStatusFilters
{
get
{
return new[] { "Label 1", "Label 2", "Label 3" }
}
}
}
and inside the view you could use the helper:
#Html.CheckBoxListFor(x => x.SelectedStatusFilters, Model.AvailableStatusFilters)
Here is another implementation that will better support bootstrap button-group labels (as it requires them to be seperated) and enum type selected values.
public static IHtmlString CheckboxListFor<TModel, TKey>(this HtmlHelper<TModel> helper, Expression<Func<TModel, IEnumerable<TKey>>> ex, Dictionary<TKey, string> i_PossibleOptions, object i_LabelHtmlAttributes)
where TKey : struct, IConvertible
{
var metadata = ModelMetadata.FromLambdaExpression(ex, helper.ViewData);
var selectedValues = (IEnumerable<TKey>)metadata.Model;
var name = ExpressionHelper.GetExpressionText(ex);
return helper.CheckboxList(name, selectedValues, i_PossibleOptions, i_LabelHtmlAttributes);
}
private static IHtmlString CheckboxList<TKey>(this HtmlHelper helper, string name, IEnumerable<TKey> i_SelectedValues, Dictionary<TKey, string> i_PossibleOptions, object i_LabelHtmlAttributes)
where TKey : struct, IConvertible
{
if (!typeof(TKey).IsEnum) throw new ArgumentException("T must be an enumerated type");
var result = new StringBuilder();
foreach (var option in i_PossibleOptions)
{
var label = new TagBuilder("label");
label.MergeAttributes(new RouteValueDictionary(i_LabelHtmlAttributes));
label.Attributes["for"] = string.Format("{0}",option.Key.ToString());
label.InnerHtml = option.Value;
var checkbox = new TagBuilder("input");
checkbox.Attributes["type"] = "checkbox";
checkbox.Attributes["name"] = name;
checkbox.Attributes["id"] = string.Format("{0}", option.Key.ToString());
checkbox.Attributes["value"] = option.Key.ToString();
bool isChecked = ((i_SelectedValues != null) && (i_SelectedValues.Contains(option.Key)));
if ( isChecked )
{
checkbox.Attributes["checked"] = "checked";
}
result.Append(checkbox);
result.Append(label);
}
return new HtmlString(result.ToString());
}
And then the View Model looks like that:
public class FaultListFilters
{
[Display(ResourceType = typeof(FaultManagementStrings), Name = "SearchKeyword")]
public string SearchKeyword { get; set; }
public Dictionary<Fault.eFaultStatus, string> PossibleFaultStatuses
{
get
{
var possibleFaultStatuses = new Dictionary<Fault.eFaultStatus, string>();
possibleFaultStatuses.Add(Fault.eFaultStatus.Open, FaultManagementStrings.OpenStatus);
possibleFaultStatuses.Add(Fault.eFaultStatus.InProgress, FaultManagementStrings.InProgressStatus);
possibleFaultStatuses.Add(Fault.eFaultStatus.Close, FaultManagementStrings.ClosedStatus);
return possibleFaultStatuses;
}
}
public IEnumerable<Fault.eFaultStatus> SelectedFaultStatuses { get; set; }
public FaultListFilters()
{
SearchKeyword = null;
SelectedFaultStatuses = new[] { Fault.eFaultStatus.Open, Fault.eFaultStatus.InProgress };
}
}
and the usage remains the same (except i have added the label html attributes)
<div class="btn-group">
#Html.CheckboxListFor(m => m.FaultListFilters.SelectedFaultStatuses, Model.FaultListFilters.PossibleFaultStatuses, new { Class="btn"})
</div>

solution to the asp.net mvc drop down list selected value overrider problem

I wrote a helper method to display enums from my model in my asp.net MVC application as drop down lists in my views.
Here is my code for that:
public static List<SelectListItem> CreateSelectItemList<TEnum>(object enumObj,
string defaultItemKey,
bool sortAlphabetically,
object firstValueOverride)
where TEnum : struct
{
var values = (from v in (TEnum[])Enum.GetValues(typeof(TEnum))
select new
{
Id = Convert.ToInt32(v),
Name = ResourceHelpers.GetResourceValue(AppConstants.EnumResourceNamespace,
typeof(TEnum).Name, v.ToString())
});
return values.ToSelectList(e => e.Name,
e => e.Id.ToString(),
!string.IsNullOrEmpty(defaultItemKey) ? ResourceHelpers.GetResourceValue(AppConstants.EnumResourceNamespace, defaultItemKey) : string.Empty,
enumObj,
sortAlphabetically,
firstValueOverride);
}
This actually generates the select item list:
public static List<SelectListItem> ToSelectList<T>(
this IEnumerable<T> enumerable,
Func<T, string> text,
Func<T, string> value,
string defaultOption,
object selectedVal,
bool sortAlphabetically,
object FirstValueOverride)
{
int iSelectedVal = -1;
if(selectedVal!=null)
{
try
{
iSelectedVal = Convert.ToInt32(selectedVal);
}
catch
{
}
}
var items = enumerable.Select(f => new SelectListItem()
{
Text = text(f),
Value = value(f),
Selected = (iSelectedVal > -1)? (iSelectedVal.ToString().Equals(value(f))) : false
});
#region Sortare alfabetica
if (sortAlphabetically)
items = items.OrderBy(t => t.Text);
#endregion Sortare alfabetica
var itemsList = items.ToList();
Func<SelectListItem, bool> funct = null;
string sValue = string.Empty;
SelectListItem firstItem = null;
SelectListItem overridenItem = null;
int overridenIndex = 0;
if (FirstValueOverride != null)
{
sValue = FirstValueOverride.ToString();
funct = (t => t.Value == sValue);
overridenItem = itemsList.SingleOrDefault(funct);
overridenIndex = itemsList.IndexOf(overridenItem);
if (overridenItem != null)
{
firstItem = itemsList.ElementAt(0);
itemsList[0] = overridenItem;
itemsList[overridenIndex] = firstItem;
}
}
if(!string.IsNullOrEmpty(defaultOption))
itemsList.Insert(0, new SelectListItem()
{
Text = defaultOption,
Value = "-1"
});
return itemsList;
}
These is the method I call:
public static MvcHtmlString EnumDropDownList<TEnum>(this HtmlHelper htmlHelper,
object enumObj,
string name,
string defaultItemKey,
bool sortAlphabetically,
object firstValueOverride,
object htmlAttributes)
where TEnum : struct
{
return htmlHelper.DropDownList(name,
CreateSelectItemList<TEnum>(enumObj,
defaultItemKey,
sortAlphabetically,
firstValueOverride),
htmlAttributes);
}
Now I am having the problem described here
When I call this helper method and the input's name is the same as the property's name the selected value doesn't get selected.
The alternate solution described there doesn't work for me. The only solution that works is changing the name and not using the model binding using FormCollection instead.
I don't like this workaround because I can't use validation any more using the ViewModel pattern and I have to write some extra code for every enum.
I tried writing a custom model binder to compensate for this somehow but none of the methods I can override there gets called when I start the action.
Is there any way to do this without using FormCollection?
Can I somehow intercept ASP.NET MVC when it tries to put the value into my input field and make it select the right value?
Thank you in advance.
I have a sollution now
Here is the code for the EnumDropDownList function the other functions are listed in the question:
public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper,
object enumObj,
string name,
string defaultItemKey,
bool sortAlphabetically,
object firstValueOverride,
object htmlAttributes)
{
StringBuilder sbRezultat = new StringBuilder();
int selectedIndex = 0;
var selectItemList = new List<SelectListItem>();
if (enumObj != null)
{
selectItemList = CreateSelectItemList(enumObj, defaultItemKey, true, null);
var selectedItem = selectItemList.SingleOrDefault(item => item.Selected);
if (selectedItem != null)
{
selectedIndex = selectItemList.IndexOf(selectedItem);
}
}
var dict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
TagBuilder tagBuilder = new TagBuilder("select");
tagBuilder.MergeAttribute("name", name,true);
bool bReadOnly = false;
//special case for readonly
if(dict.ContainsKey("readonly"))
{
//remove this tag it won't work the way mvc renders it anyway
dict.Remove("readonly");
bReadOnly = true;
}
//in case the style element is completed if the drop down is not readonly
tagBuilder.MergeAttributes(dict, true);
if (bReadOnly)
{
//add a small javascript to make it readonly and add the lightgrey style
tagBuilder.MergeAttribute("onchange", "this.selectedIndex=" + selectedIndex + ";",true);
tagBuilder.MergeAttribute("style", "background: lightgrey", true);
}
sbRezultat.Append(tagBuilder.ToString(TagRenderMode.StartTag));
foreach (var option in selectItemList)
{
sbRezultat.Append(" <option value='");
sbRezultat.Append(option.Value);
sbRezultat.Append("' ");
if (option.Selected)
sbRezultat.Append("selected");
sbRezultat.Append(" >");
sbRezultat.Append(option.Text);
sbRezultat.Append("</option>");
}
sbRezultat.Append("</select>");
return new MvcHtmlString(sbRezultat.ToString());
}
I also wrote a generic function of type For (EnumDropDownFor):
public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string defaultItemKey,
bool sortAlphabetically,
object firstValueOverride,
object htmlAttributes)
where TProperty : struct
{
string inputName = GetInputName(expression);
object selectedVal = null;
try
{
selectedVal = htmlHelper.ViewData.Model == null
? default(TProperty)
: expression.Compile()(htmlHelper.ViewData.Model);
}
catch//in caz ca e ceva null sau ceva de genu'
{
}
return EnumDropDownList(htmlHelper,
selectedVal,
inputName,
defaultItemKey,
sortAlphabetically,
firstValueOverride,
htmlAttributes);
}
and some helper methods:
public static string GetInputName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
{
if (expression.Body.NodeType == ExpressionType.Call)
{
MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
string name = GetInputName(methodCallExpression);
return name.Substring(expression.Parameters[0].Name.Length + 1);
}
return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);
}
private static string GetInputName(MethodCallExpression expression)
{
MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression;
if (methodCallExpression != null)
{
return GetInputName(methodCallExpression);
}
return expression.Object.ToString();
}

Resources