6

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this works thanks. I assumed you couldn't pass the raw date time back as it would corrupt the URL, but it seems the model binder handles this as you have said.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.