user3802347
user3802347

Reputation: 108

ASP.NET MVC 4 Route Issue

I am having an issue with Routing. I am using the JavaScript function below to do a post to my controller StudentSearch. When I did a post, it only passed the first parameter. The page is null which is expected; however, the start and end Date have date values, but both parameters are both null. What am I missing here? I read the documentation and search online, and I have not had any success so far.

//Javascript function
 findStudent function()
  {  
    var SearchValue= $("#Search").val();
    var StartDate = $('#StartDate').val();
    var EndDate = $('#EndDate').val();

    var url = '@Url.Action("Search")';

    location.href = url + "/" + SearchValue + "/" + StartDate +"/" + EndDate+;
}

//This is the ActionResult in the controller
public ActionResult Search(string SearchValue, string StartDate , string EndDate)
  {
     //EndDate and STart Date are null here.
   }

//the route section in my RouteConfig.cs file

routes.MapRoute(
                name: "Search",
                url: "StudentSearch/Search/{SearchValue}/{StartDate}/{EndDate}",
                defaults: new { controller = "StudentSearch", action = "Search", 
                SearchValue = UrlParameter.Optional,StartDate=UrlParameter.Optional, 
                EndDate = UrlParameter.Optional}
                );

update at 02:50 PM: After reading Chris comment, I modified the code. It did not route to the StudentSearch controller. I got a 404 page not found instead. As you can see I passed in Jane for searchvalue and student1, student2 respectively for start and enddate (it was not a problem since the parameter is expected a string). .../StudentSearch/Search/Jane/student1/student2

Upvotes: 0

Views: 65

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

Not sure what you're expecting here. The url variable is going to resolve to the string '/StudentSearch/Search', because you're passing empty strings for all the route params. That's actually pointless, anyways. You'd get the same with just @Url.Action("Search").

Then you append the variable SearchValue to this string, which comes form $('#Search').val(). And, that's it. StartDate and EndDate are never used, especially not in constructing the URL.

Then your route itself doesn't accept anything but SearchValue as a wildcard string. Even if you did append StartDate and EndDate to the URL, everything would just go into the SearchValue param and your actual StartDate and EndDate action parameters would still be null. Your route would need to be something like:

url: "StudentSearch/Search/{SearchValue}/{StartDate}/{EndDate}",

To fill all the parameters properly.

Upvotes: 1

Related Questions