简体   繁体   中英

MVC Controller parameters not required but optional

Hi I'm using a HttpPost from a view to send some parameters to a controller, the db gets filtered according to those given parameters. BUT the parameters should be optional and if not given the controller just ignores them. But this seems to be impossible?

VIEW

@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>   

}

CONTROLLER

I thought it would be possible to just check if the parameter was null or not and change the function accordingly:

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

}

But I get an instant error that the parameters should be given, is there a possibility to set these parameters to optional?

将参数声明为可为空

public ActionResult Index(string dropdownlist, DateTime? datepicker)

声明可为空的参数

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

您可以通过将参数设置为可选参数并分配默认值null来解决此问题:

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

try this it can be work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM