开发者

ASP.NET MVC Populating a DropDownList with a value from the view

In my controller I have this:

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

and then I bind it to my view using

<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'm using the spark view engine so this DropDownList is getting rendered to the page via a loop. This means that the selected value of the dropdown list will change on each iteration of the loop.

What I 开发者_JAVA技巧can't work out is how to pass in the value I want to set the DropDownList to based on the value that is currently being rendered to the screen.


So after a bit of playing around I worked it out:

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

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

and then construct 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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜