Which way I can implement dropdown list for enum values?
I have a enum like this:
public enum ValueEnum : byte
{
[Description("Value 1")]
Value1 = 1,
[Description("Value 2")]
Value2 = 2,
[Description("Value 3")]
Value3 = 4
}
and I want to get single value from multiple select on server side instead of list of selected values:
public ActionResult ValueAction(ValueEnum result)
{
//too many code
return View();
}
where result can be ValueEnum.Value1
or ValueEnum.Value1 | ValueEnum.Value3
Is there a way to do it without client side sum?
Dropdown lists are one of the most flexible elements in HTML. It is similar to that of the radio input, that is, only one item can be selected from a group of items by default. However, when the multiple attribute is used with the <select> element, we can enable the selection of multiple options from the list.
Yes. If you do not care about the order, use EnumSet , an implementation of Set . enum Animal{ DOG , CAT , BIRD , BAT ; } Set<Animal> flyingAnimals = EnumSet.
Multi select dropdown list is used when a user wants to store multiple values for the same record, whereas dropdown list is used to store a single value for a record. You can create custom categories of either dropdown list or multi select dropdown list and define items in each category.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
I solved it on the client side with the following behaviour:
Get
method:
[HttpGet]
public ActionResult ValueAction(ValueEnum result)
{
//irrelevant code
ViewBag.Values = Enum.GetValues(typeof(ValueEnum))
.OfType<ValueEnum>()
.Select(x => new SelectListItem
{
Text = x.GetCustomAttribute<DescriptionAttribute>().Description,
Value = ((byte)x).ToString()
});
return View();
}
Razor:
@using(Html.BeginForm())
{
@*irrelevant code*@
@Html.DropDownList("valueEnum", (IEnumerable<SelectListItem>)ViewBag.Values, new { multiple="multiple", id="enumValues" })
@*Here would be stored result value for this flagged enum*@
<input type='hidden' name='resultValue' id='hidden-enum-value' />
@*irrelevant code*@
<input type="submit" value="Submit" />
}
JS:
$(function() {
$('form').submit(function() {
var vals = $('#enumValues').val();
var result = 0;
for(let i = 0; i < vals.length; i++) {
result += Number(vals[i]);
}
$('#hidden-enum-value').val(result);
});
});
Post
method:
[HttpPost]
public ActionResult ValueAction(ValueEnum resultValue)
{
//irrelevant code
return View();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With