2014-11-14 36 views
0

我需要向我的MVC控制器方法發送一個id,該方法是從json調用發送的。最後,我需要刷新屏幕。這工作正常:將多個參數傳遞給控制器​​

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

但是,我現在需要發送多個參數。所以,我的控制器方法需要命名的兩個參數,和我嘗試打電話給我的控制器是這樣的:

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

但我得到的錯誤:

A potentially dangerous Request.Path value was detected from the client (&).

有沒有更好的方式來做到這一點 - 或者,我該如何解決?

+3

您缺少'?'。 – undefined 2014-11-14 23:24:17

+0

嘗試'window.location.href ='/ Reports/SpendingByCategoryByMonth?categoryId ='+ categoryId +'&subCategoryId ='+ subCategoryId;' – 2014-11-14 23:24:26

回答

3

在第一種情況:

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

你probally使用,當你創建一個新的項目所產生的默認路由(該ID是一個可選PARAM):

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

您的網址有潛在的XSS字符int it。

第二url probally不會被你的服務器支持(僅當您創建了一個相應的路由),但如果它是你應該閱讀herehere解決您的問題。

最好的做法就是用這樣的網址:

/Controller/Action?param1=abc&param2=deg 
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;

例如

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

控制器

public ActionResult SpendingByCategoryByMonth(int categoryId, int subCategoryId)

無需任何&?人物都在href網址。

請注意,我假設類別Id值爲int,如果不是,則只需刪除路由映射的constraints部分。