返回带有一个动作结果的多个选择列表

本文关键字:选择 列表 结果 有一个 返回 | 更新日期: 2023-09-27 18:05:13

我想在一个视图中显示2个SelectList。显然,我只能使用1个ActionResult来渲染视图。

public ActionResult IndexStudents(Docent docent, int lessonid, int classid)
        {
            return View(new SelectList(docent.ReturnStudentsNormalAsString(lessonid, classid)));
            return View(new SelectList(docent.ReturnStudentsNoClassAsString(lessonid, classid)));            
        }

当然,这行不通。我怎样才能修好它呢?也许是利用字典?

我希望我的输出看起来像这样:

<div class="editor-field">
                     <%: Html.DropDownList("IndexStudentsNormal", 
                    Model as SelectList) %> 
 </div>
<div class="editor-field">
                     <%: Html.DropDownList("IndexStudentsNoClass", 
                    Model as SelectList) %> 
 </div>

所以我想使用2个模型,每个选择列表一个…一组是普通学生,另一组是不上课的学生。

我怎么能那样做呢?

返回带有一个动作结果的多个选择列表

您需要用两个SelectLists定义一个模型:

// new class in your project
public class SelectListModel
{
    public SelectList SL1 { get; set; }
    public SelectList SL2 { get; set; }
}

// updated version of your ActionResult    
public ActionResult IndexStudents(Docent docent, int lessonid, int classid)
{
    var myslm = new SelectListModel 
    {
        SL1 = new SelectList(docent.ReturnStudentsNormalAsString(lessonid, classid),
        SL2 = new SelectList(docent.ReturnStudentsNoClassAsString(lessonid, classid)
    };
    return View(myslm);
}

// updated view code
<div class="editor-field">
    <%: Html.DropDownList("IndexStudentsNormal", Model.SL1 as SelectList) %>  
</div>
<div class="editor-field">
    <%: Html.DropDownList("IndexStudentsNoClass", Model.SL2 as SelectList) %>
</div>

您可以使用ViewDataViewBag将其传递给视图

    public ActionResult IndexStudents(Docent docent, int lessonid, int classid)
    {
        ViewData["list1"] = new SelectList(docent.ReturnStudentsNormalAsString(lessonid, classid)));
        ViewData["list2"] = (new SelectList(docent.ReturnStudentsNoClassAsString(lessonid, classid)));
        return View();            
    }

<div class="editor-field">
                     <%: Html.DropDownList("IndexStudentsNormal", 
                    ViewData["list1"] as SelectList) %> 
 </div>
<div class="editor-field">
                     <%: Html.DropDownList("IndexStudentsNoClass", 
                    ViewData["list2"] as SelectList) %> 
 </div>