ASP.NET MVC使用视图中的值填充DropDownList

时间:2022-11-15 04:02:08

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.

请注意,我正在使用spark视图引擎,因此DropDownList将通过循环呈现给页面。这意味着下拉列表的选定值将在循环的每次迭代中更改。

What I 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.

我无法解决的是如何根据当前呈现给屏幕的值传递我想要设置DropDownList的值。

1 个解决方案

#1


1  

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>

#1


1  

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>