ajaxasp.net-mvcasp.net-mvc-ajaxurl.action

Passing date parameters to @url.action via ajax


In my ASP.NET MVC 4 app, I'm using the following JAX code taken from this StackOverflow post to pass Date parameters to a controller but I am getting the following http 404 error: "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. Requested URL /myWebApp/myController/myAction/01/01/2014/12/31/2014"

Here the input controls txtFrom and txtTo have the values 01/01/2014 and 12/31/2014 respectively. the issue is that MVC is probably interpreting each date as three different parameters. How can we fix it. I tried replacing $('#txtFrom').val() with $('#txtFrom').val().replace("///g", "_") but it does not work.

window.location.href = '@Url.Action("myAction")/' + $('#txtFrom').val() + '/' + $('#txtTo').val();

Action method:

public ActionResult myAction(string startDate, string endDate)
{
 //simple code here to use the input parameters
}

Solution

  • You could either format the date string with Razor

    @HttpUtility.UrlEncode(date)
    

    with javascript

    encodeURIComponent(date)
    

    or pass the date as ticks (milliseconds since Epoch) instead of the human-readable format.

    Edit:

    After experimenting with this and a bit of research it seems the slash and %2f encoding causes all kinds of problems. Stick to the millisecond representation for a date and not worry about passing the slash.