Ajax GET参数到MVC 5控制器

时间:2015-04-23 13:10:58

标签: ajax asp.net-mvc

我想知道为什么当我的参数被调用ajax时,Controllerid的调用有效,而当它被称为accountNo或{{1}时无效}}

的Ajax

accountId

控制器

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

在我的 public JsonResult GetDeferredAccountDetailsByAccount(int id) { var details = _deferredAccountDetailsService.GetDeferredAccountDetailsByAccount(id); return Json(details, JsonRequestBehavior.AllowGet); } 中 - 如果参数为Controller,一切正常。

enter image description here

如果我将int id参数更改为Controller,我会收到500错误,指出我的参数为accountNum

enter image description here

因此,它实际上只是控制器参数的命名,它决定了我的null请求是否成功。是因为它是JSON编码的,我没有在我的GET方法中指定数据模型/格式吗?

如果答案存在,我道歉,因为我没有遇到过它。

2 个答案:

答案 0 :(得分:5)

这是因为RouteConfig.cs默认情况下将路线的第三个组成部分定义为变量id

您可以通过指定URL

来访问该控制器

/DeferredAccount/GetDeferredAccountDetailsByAccount/?accountNum=1

使用属性路由

还有另一种更精细的方式,即使用MVC 5为路由提供服务,称为属性路由。

修改RouteConfig.cs
添加routes.MapMvcAttributeRoutes();

编辑控制器

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

MSDN: Attribute Routing in ASP.NET MVC 5

答案 1 :(得分:0)

您可以在RouteConfig.cs文件中将Route放在Route下面

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