Search code examples
jqueryasp.net-mvcjsonasp.net-mvc-routing

ASP.NET MVC Pass mutiple params from getJson to controller


I am making a call to a controller action in javascript using the getJson method. I need to pass two parameters to my action method on the controller, but I am struggling to do so. I do not fully understand the routing tables and not sure if this is what I need to use to get this working. Please see example below of what I am trying to do.

var action = "<%=Url.Content('~/Postcode/GetAddressResults/')%>" + $get("Premise").value + "/" + $get("SearchPostcode").value
$.getJSON(action, null, function(data) {
  $("#AddressDropDown").fillSelect(data);
});

This is my route which I don't understand how to make use of...

routes.MapRoute(
 "postcode",
 "Postcode/GetAddressResults/{premise}/{postcode}",
 new {
  controller = "Motor", action = "GetAddressResults",
    premise = "", postcode = ""
 });

Solution

  • You're definitely on the right path, though I would need to see your controller to know for sure. It would need to look something like this:

    public ActionResult GetAddressResults(string premise, string postcode)
    {
      //Do something.
      return Json(AddressService.GetResultsOfSomeKind(premise, postcode);
    }
    

    Set a breakpoint on your ActionResult so you know it's being called. If it's not, use Firefox and check the Error Console for syntax errors (the code you posted has some).

    UPDATE:

    What is

    $get("Premise").value? 
    

    To get an input's value via jQuery, use:

    $("#fieldid").val();
    

    I recommend using the Firebug plugin for Firefox. That way you'll know exactly at which point your javascript is breaking. Most likely you'll find that your "var action =" statement is not properly appending the form field values on the client side before the $.getJSON call sends a request to your controller.