简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM