Warm tip: This article is reproduced from stackoverflow.com, please click
c# razor model-view-controller

Filter button won't reload and filter information

发布于 2020-03-27 10:26:33

Hello I'm trying to filter by graduation status in my Index pages with a dropdown filter but when clicking the Process button the pages wont filter...

What am I doing wrong here?

Index Page showing filter button

View :

@using (@Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = 
     "FilterForm" }))
                        {
                            <table>
                                <tr>
                                    <th>


        @Html.DropDownList("GraduationStatus", 
         null, htmlAttributes: new { @class = "form-control" })
                                        </th>
                                        <th>
                                            <button type="submit" class="btn btn- 
          primary btn-lg"> Process !</button>
                                        </th>
                                    </tr>
                                </table>
                            }

Controller :

 public ActionResult Index(string graduationStatus)
        {
            ViewBag.GraduationStatus = new SelectList(db.Graduated_Students.Select(m => m.GraduationStatus).Distinct().ToList());

            var graduates = db.Graduated_Students.Where(student => student.GraduationStatus != null);

            return View(graduates.ToList());
        }
Questioner
Martin
Viewed
75
Muhammad Ali 2019-07-04 00:11

because you don't need to filter on initail page load. graduationStatus will be null on initial load so add a condition to check if graduationStatus has some value. like this

   public ActionResult Index(string graduationStatus)
    {
      var graduates = db.Graduated_Students.Where(student => student.GraduationStatus != null);
        ViewBag.GraduationStatus = new SelectList(db.Graduated_Students.Select(m => m.GraduationStatus).Distinct().ToList());
         if(!string.IsNullOrEmpty(graduationStatus))
         {
             graduates = graduates .Where(student => student.GraduationStatus == graduationStatus);
         }


        return View(graduates.ToList());
    }