开发者

Return muliple selectlist with one actionresult

开发者 https://www.devze.com 2023-03-27 07:30 出处:网络
I\'d like to display 2 SelectList in one View. So obviously, I can only use 1 ActionResult to render the view.

I'd like to display 2 SelectList in one View. So obviously, I can only use 1 ActionResult to render the view.

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)));            
        }

But of course, this does not work. How could I fix it? Maybe making use of a Dictionary?

I want my output look like this:

<div class="editor-field">
                     <%: Html.DropDownList("IndexStudentsNormal", 
                    Mod开发者_JAVA技巧el as SelectList) %> 
 </div>
<div class="editor-field">
                     <%: Html.DropDownList("IndexStudentsNoClass", 
                    Model as SelectList) %> 
 </div>

So I'd like to use 2 models, one for each selectlist... one with normal students and one with students who are not subscribed for lessons.

How could I do that?


You need to define a model with two 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>


You can use the ViewData or ViewBag to pass it to view

    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();            
    }

Then in 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>
0

精彩评论

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