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?
DateTime? datepicker