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

时间:2014-06-11 11:42:50

标签: c# asp.net-mvc

您好我在视图中使用HttpPost将一些参数发送到控制器,db会根据这些给定的参数进行过滤。但参数应该是可选的,如果没有给出,控制器就会忽略它们。但这似乎不可能?

查看

@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

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

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

}

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

4 个答案:

答案 0 :(得分:1)

将参数声明为可为空的

public ActionResult Index(string dropdownlist, DateTime? datepicker)

答案 1 :(得分:0)

声明可以为空的参数

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

答案 2 :(得分:0)

您可以通过使参数可选并指定默认值null来解决此问题:

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

答案 3 :(得分:0)

试试这可以起作用

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