将多个参数传递给控制器

时间:2014-11-14 23:22:30

标签: jquery asp.net-mvc

我需要向我的MVC控制器方法发送一个id,该方法是从json调用发送的。最后,我需要刷新屏幕。这很好用:

window.location.href = '/Reports/SpendingByCategoryByMonth/' + categoryId;

但是,我现在需要发送多个参数。所以,我的控制器方法有两个名为的参数,我试着像这样调用我的控制器:

window.location.href = '/Reports/SpendingByCategoryByMonth/categoryId=' + categoryId + '&subCategoryId=' + subCategoryId;

但我收到错误:

  

从中检测到潜在危险的Request.Path值   客户(&)。

有更好的方法吗 - 或者,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

在第一种情况下:

window.location.href = '/Reports/SpendingByCategoryByMonth/' + categoryId;

您可能会使用在创建新项目时生成的默认路由(ID是可选参数):

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults);

您的网址没有在其中包含潜在的XSS字符。

您的服务器可能不支持第二个网址(仅当您创建了相关路由时),但如果是,则应阅读herehere以解决您的问题。

最佳做法是使用这样的网址:

/Controller/Action?param1=abc&param2=deg

答案 1 :(得分:0)

为什么不使用MVC路由的强大功能来帮助你?

创建新路线

routes.MapRoute(
    name: "Spending report by month",
    url : "Reports/SpendingByCategoryByMonth/{categoryId}/{subCategoryId}",
    defaults: new { controller =  "Reports", action = "SpendingByCategoryByMonth" },
    constraints : new { categoryId = @"\d+", subCategoryId = @"\d+" });

确保在

之前显示
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

然后你可以将href更改为:

window.location.href = '/Reports/SpendingByCategoryByMonth/' + categoryId + '/' + subCategoryId;

e.g。

http://localhost:54313/Reports/SpendingByCategoryByMonth/1/2

<强>控制器

public ActionResult SpendingByCategoryByMonth(int categoryId, int subCategoryId)

href网址中根本不需要任何&?个字符。

注意,我假设类别ID值为int,如果不是,则只需删除路由映射的constraints部分。