I have a web page that uses a date range filter, the selected date range is passed back to the controller when the user clicks the 'filter' action link and the controller returns the 'index' view with the filtered model data.
View
@Html.ActionLink("Filter", "FilterDateRange", new { from = Url.Encode(Model.FromDate.ToString()), to = Url.Encode(Model.ToDate.ToString()) }, null)
Controller
public ActionResult FilterDateRange(string from, string to)
{
var fromDate = DateTime.Parse(HttpUtility.UrlDecode(from));
var toDate = DateTime.Parse(HttpUtility.UrlDecode(to));
//do stuffs
return View("Index", statsPages);
}
My question is, is there a more elegant way to do this? Currently the date value is being url encoded in the view and then url decoded in the controller, I would rather the method within the controller take date time parameters rather than strings, it seems a little hacky as it is.
Thanks.
Why not just use DateTime parameters?
@Html.ActionLink("Filter", "FilterDateRange", new { from = Model.FromDate, to = Model.ToDate }, null)
public ActionResult FilterDateRange(DateTime from, DateTime to)
{
var fromDate = from;
var toDate = to;
//do stuffs
return View("Index", statsPages);
}
If you let the model binder do its thing, you won't have to worry about encoding, decoding, or parsing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With