使用一个actionresult返回多个选择列表

时间:2011-08-09 14:19:11

标签: c# .net asp.net-mvc model selectlist

我想在一个视图中显示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个模型,每个选择列表一个...一个是普通学生,另一个是没有订阅课程的学生。

我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

您需要使用两个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>

答案 1 :(得分:0)

您可以使用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>