Search code examples
asp.net-mvcasp.net-mvc-5html-helper

Set The selected Value of a Multiselect from Controller to View after submitting an invalid Model


I am using a Multiselect DropDownList to generate a multiple <select> I was able to generate it and was working fine.

But If I try to submit it using the parameters:

  1. Name = null
  2. ObjAOption = [1,2] // assume I selected 2 options in my multiselect

ObjAOption will just select option value='1' instead of select options 1, and 2.

Is there any way I can get back the selected options and pass it back to my view by setting it in my controller? I would love to use HTML helper and not to use jQuery or javascript on this part.

Controller:

public ActionResult AddObjectA(AddModel am){
      if(ModelState.IsValid){
            //Save
      }
      else {
            am.ObjA = // new List of ObjectA with atleast 4 option
            return View("MyView",am);
      }
}

View:

@Html.LabelFor(model => model.ObjA, "Object A")
@Html.DropDownList("ObjAOption", new MultiSelectList(Model.ObjA, "Key", "Name"), "-- Select Object A--", new { @class = "custom-select custom-select-sm", multiple="" })
@Html.ValidationMessageFor(m => m.ObjAOption, "", new { @class = "text-danger" })

Model:

public class AddModel {
        [Required]
        public String Name {get;set;}
        public IEnumerable<ObjectA> ObjA{ get; set; }
        [Required(ErrorMessage = "Please select at least one option")]
        public List<int>ObjAOption{ get; set; }
}

public class ObjectA {
        public int Key {get;set;}
        public string Name {get;set;}
}


Solution

  • Solution:

    I scrapped out my DropDownList and tried using ListBoxFor as discussed here