戳戳猫的小窝
更新日志
关于
# 完善控制器 为HomeController注入SearchService实例,给Index动作添加视图模型参数,并调用SearchService的GetList方法,最后将视图模型返回给视图。 代码如下: ``` public class HomeController(SearchService searchService) : Controller { public IActionResult Index(SearchViewModel model) { return View(searchService.GetList(model)); } } ``` # 设置模型和标题 ``` @model SearchViewModel @{ ViewBag.Title = "首页"; } ``` # 添加查询部分 ``` <form method="post"> <div class="field is-grouped"> <div class="field has-addons"> <div class="control"> <a class="button is-static">专业</a> </div> <div class="control"> <div class="select"> <select asp-for=MajorId asp-items=Model.Majors hx-get="/Student/GetClassSelectPartial" hx-target="#ClassId" hx-include="#GradeId,#ClassId" hx-swap="outerHTML"> <option value="">请选择</option> </select> </div> </div> </div> <div class="field has-addons"> <div class="control"> <a class="button is-static">年级</a> </div> <div class="control"> <div class="select"> <select asp-for=GradeId asp-items=Model.Grades hx-get="/Student/GetClassSelectPartial" hx-target="#ClassId" hx-include="#MajorId,#ClassId" hx-swap="outerHTML"> <option value="">请选择</option> </select> </div> </div> </div> <div class="field has-addons"> <div class="control"> <a class="button is-static">班级</a> </div> <div class="control"> <div class="select"> <input asp-for="ClassId" hx-get="/Student/GetClassSelectPartial" hx-trigger="load" hx-include="#MajorId,#GradeId" hx-swap="outerHTML"> </div> </div> </div> <div class="field has-addons"> <div class="control"> <a class="button is-static">性别</a> </div> <div class="control"> <div class="select"> <select asp-for=Gender> <option value="">请选择</option> <option value="false">男</option> <option value="true">女</option> </select> </div> </div> </div> <div class="field has-addons"> <div class="control"> <a class="button is-static">姓名</a> </div> <div class="control"> <input asp-for=Name class="input"> </div> </div> <div class="field has-addons"> <div class="control"> <a class="button is-static">学号</a> </div> <div class="control"> <input asp-for=Number class="input"> </div> </div> <div class="field"> <button class="button is-primary">查找</button> </div> </div> </form> ``` 可以看到Major,Grade,Class的下拉栏请求的地址均是**/Student/GetClassSelectPartial**。 # 查询结果列表 ``` <table class="table is-bordered is-striped is-hoverable is-fullwidth"> <thead> <tr> <th>学号</th> <th>姓名</th> <th>专业</th> <th>年级</th> <th>班级</th> <th>性别</th> <th>生日</th> </tr> </thead> <tbody> @foreach (var result in Model.Results) { <tr> <td>@result.Number</td> <td>@result.Name</td> <td>@result.MajorName</td> <td>@result.GradeName</td> <td>@result.ClassName</td> <td>@(result.Gender?"女":"男")</td> <td>@result.Birthday.ToString("yyyy年MM月dd日")</td> </tr> } </tbody> </table> ``` 通过Results可以获得数据列表。 > 为什么只需要1个Action就能完成此操作?之前不是需要一个post请求吗? > > 因为如果不指定请求类型,Action能接受所有请求类型,包括get请求和post请求。 > > 当我们通过浏览器直接进入首页,发送的是get请求,此时查询数据为空,因此可以显示所有数据。 > > 而当我们点击按钮去筛选时,发送的是post请求,此时会根据条件查询数据。
完善控制器和视图