Mark C.
Mark C.

Reputation: 6460

Ajax GET Parameter to MVC 5 Controller

I'm wondering why my ajax call to my Controller works when my Parameter is called id and doesn't work when it's called accountNo or accountId.

Ajax

 $.ajax({
             type: "GET",
             dataType: "json",
             cache: false,
             url: config.url.root + "/DeferredAccount/GetDeferredAccountDetailsByAccount/" + accountNo
                });

Controller

 public JsonResult GetDeferredAccountDetailsByAccount(int id)
        {
            var details = _deferredAccountDetailsService.GetDeferredAccountDetailsByAccount(id);

            return Json(details, JsonRequestBehavior.AllowGet);
        }

In my Controller - if the parameter is int id everything works.

enter image description here

If I change the Controller parameter to, let's say, accountNum, I receive a 500 error stating that my parameter is null.

enter image description here

So, it's literally just the naming of the Parameter for the Controller that dictates the success of my GET request or not. Is it because it's JSON encoded, and I'm not specifying the data model/format in my ajax method?

If an answer exists for this, I apologize as I haven't come across it.

Upvotes: 0

Views: 1768

Answers (2)

Abbas Galiyakotwala
Abbas Galiyakotwala

Reputation: 3019

you may put below Route on top in your RouteConfig.cs file

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "DeferredAccount", action = "GetDeferredAccountDetailsByAccount", id = UrlParameter.Optional }
);

Upvotes: 0

Dan
Dan

Reputation: 1018

This is because the RouteConfig.cs by default defines the third component of your route as the variable id.

You can get to that controller by specifying the URL

/DeferredAccount/GetDeferredAccountDetailsByAccount/?accountNum=1

Using attribute routing

There is another more fine-grained way of serving your routing with MVC 5 known as attribute routing.

Edit RouteConfig.cs
Add routes.MapMvcAttributeRoutes();

Edit Controller

[Route("/whatever/path/i/like/{accountNum:int}")]
public JsonResult GetDeferredAccountDetailsByAccount(int accountNum)
{
    [...]
}

MSDN: Attribute Routing in ASP.NET MVC 5

Upvotes: 5

Related Questions