ASP.NET MVC Populating DropDownList with value from view

In my controller, I have the following:

ViewData["maskList"] = new SelectList(equipmentRepository.GetMasks(), "Id", "DisplayName");

      

and then I bind it to my view with

<div each="var nfa in mfa.NasalFittingAssessment">
    ${Html.DropDownList("NasalMaskTypeId", ViewData["maskList"] as IEnumerable<System.Web.Mvc.SelectListItem>, new { class = "ddl" })}                
</div>

      

Note that I am using a spark view engine, so this DropDownList gets rendered on the page through a loop. This means that the selected dropdown value will change at each iteration of the loop.

What I cannot work out is to pass in the value I want to set for the DropDownList based on the value that is currently displayed on the screen.

+2


a source to share


1 answer


So after playing around a bit, I decided:

What you want to do is just assign the shared collection in the controller like this:

ViewData["maskList"] = equipmentRepository.GetMasks();

      



and then build the selectlist on the fly from within the view like this:

<div each="var nfa in mfa.NasalFittingAssessment">
    ${Html.DropDownList("NasalFittingAssessment.NasalMaskType.Id", new SelectList(ViewData["maskList"] as IList<Equipment>, "Id", "DisplayName", nfa.NasalMaskType.Id), new { class = "ddl" })}                
</div>

      

+1


a source







All Articles