Multi select drop-down list for listing

In what order can I implement a drop-down list for enum values?

I have an enumeration 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 one value from several options on the server side instead of a list of selected values:

  public ActionResult ValueAction(ValueEnum result) { //too many code return View(); } 

where the result can be ValueEnum.Value1 or ValueEnum.Value1 | ValueEnum.Value3 ValueEnum.Value1 | ValueEnum.Value3

Is there any way to do this without the client side amount?

+5
source share
2 answers

You create a list from your Enum, as this stream offers or this and create a new SelectList with it and save it in the ViewBag, and then in your view make DropDownList or DropDownList for the helper and use the same name for the ViewBag variable as for the select element.

 //GET: ~/ValueController/ValueAction public ActionResult ValueAction() { Array values = Enum.GetValues(typeof(ValueEnum)); List<ListItem> items = new List<ListItem>(values.Length); foreach(var i in values) { items.Add(new ListItem { Text = Enum.GetName(typeof(ValueEnum), i), Value = ((int)i).ToString() }); } ViewBag.valueEnum = new SelectList(items); } 

View:

 @Html.DropDownList("valueEnum", null, htmlAttributes: new { @class = "form-control" }) 

Then MVC will automatically assign the contents of the ViewBag to the select element.

Then, in your Post action, you set its parameters to get a prime integer.

 //POST: ~/ValueController/ValueAction [HttpPost] public ActionResult ValueAction(int valueEnum) { //less code return View(); } 
0
source

I solved this on the client side with the following behavior:

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(); } 
0
source

Source: https://habr.com/ru/post/1244423/


All Articles