您好我使用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());
}
但是我得到一個即時的錯誤,應該給參數,是否有可能將這些參數設置爲可選?
聲明參數爲可爲空的DateTime? datepicker' –
事實上,這麼容易,但沒有想到它。謝謝!作爲回答,雖然它是一條評論,但不能接受...... – user3629755
已添加爲答案 –