Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing dates from view to controller mvc/c#

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.

like image 228
RobJohnson Avatar asked Oct 10 '22 00:10

RobJohnson


1 Answers

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.

like image 113
jrummell Avatar answered Oct 13 '22 11:10

jrummell