2014-06-11 50 views
0

您好我使用HttpPost從視圖發送一些參數到控制器,數據庫獲取根據給定的參數過濾。但參數應該是可選的,如果沒有給出,控制器會忽略它們。但是這似乎是不可能的?MVC控制器參數不是必需的,但可選

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> 

}

控制器

我認爲這將有可能只是檢查,如果該參數爲空或不併相應地更改功能:

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

} 

但是我得到一個即時的錯誤,應該給參數,是否有可能將這些參數設置爲可選?

+2

聲明參數爲可爲空的DateTime? datepicker' –

+0

事實上,這麼容易,但沒有想到它。謝謝!作爲回答,雖然它是一條評論,但不能接受...... – user3629755

+0

已添加爲答案 –

回答

1

聲明參數可爲空

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

工作正常,謝謝! – user3629755

0

聲明空的參數的

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

正如Stephen Muecke所說:解決方案是設置DateTime? datepicker可爲空。在字符串上,這不一定會導致字符串可以爲空。不管怎麼說,還是要謝謝你! – user3629755

+0

你不能有一個字符串?參數。字符串默認情況下已爲「空」。 – Dismissile

0

您可以通過參數可選,並指定默認設置爲NULL值,解決這個問題:

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

試試這可以工作

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