MVC控制器参数不是必需的,而是可选的

本文关键字:控制器 参数 MVC | 更新日期: 2023-09-27 18:08:12

嗨,我正在使用一个HttpPost从一个视图发送一些参数到一个控制器,数据库得到根据这些给定的参数过滤。但是参数应该是可选的,如果没有给出,控制器就会忽略它们。但这似乎是不可能的?

<

视图/strong>

@using (Html.BeginForm("Index", "Logbook")) {
 @Html.ValidationSummary(true)
       <div class="col-lg-3">
           <div class="panel panel-default">
               <div class="panel-heading">
                   <i class="fa fa-bell fa-fw"></i> Filter logbook
               </div>
               <div class="panel-body">
                   <div class="col-lg-5">
                        @Html.Label("Filter on room: ")
                        @Html.Label("Filter on date: ")
                   </div>
                   <div class="col-lg-6"> 
                        @Html.DropDownList("dropdownlist",Eindwerk.Controllers.RoomController.GetRooms(),new { @class = "btn btn-default-dropdown-toggle"})
                        @Html.TextBox("datepicker","", new { @class = "form-control" })
                   </div>
                <div>
                <button type="submit" class="btn btn-outline btn-primary btn-lg btn-block">Filter logbook</button>
                @Html.ActionLink("Remove Filter", "Index","FilterClear",new { @class = "btn btn-outline btn-success btn-lg btn-block" })
           </div>   

}

控制器

我认为可以检查参数是否为空,并相应地更改函数:

[HttpPost]
public ActionResult Index(string dropdownlist, DateTime datepicker)
{
    if(dropdownlist != null && datepicker != null)
    return View(db.Logbook.Where(p => p.Room == dropdownlist && p.Time.Day == datepicker.Month).OrderByDescending(a => a.Id).ToList());
    if(dropdownlist != null && datepicker == null)
    return View(db.Logbook.Where(p => p.Room == dropdownlist).OrderByDescending(a => a.Id).ToList());
    if(dropdownlist == null && datepicker != null)
    return View(db.Logbook.Where(p => p.Time.Day == datepicker.Month).OrderByDescending(a => a.Id).ToList());
    else
    return View(db.Logbook.OrderByDescending(p => p.Id).ToList());
}

但是我得到一个即时错误,参数应该给定,是否有可能将这些参数设置为可选的?

MVC控制器参数不是必需的,而是可选的

将参数声明为可空

public ActionResult Index(string dropdownlist, DateTime? datepicker)

声明可为空的参数

public ActionResult Index(string? dropdownlist, DateTime? datepicker)

尝试一下,它可以工作

public ActionResult Index(string dropdownlist=null, DateTime datepicker=null)

可以通过将参数设为可选并将默认值赋为null来解决这个问题:

public ActionResult Index(string dropdownlist, DateTime? datepicker = null){}