![](/img/trans.png)
[英]How to send int array from ajax call from JS to controller action as a parameter in C#
[英]Call Action in Controller From View and send parameter
我正在嘗試通過JavaScript操作在MVC中的控制器內調用方法。 javascript操作應該在控制器內部調用此方法並將一些參數發送給它。
我的Javascript代碼如下所示:
location.href = '@Url.Content("~/Areas/MyArea/MyMethod/"+Model.MyId)';
我的方法定義如下:
[HttpGet]
public ActionResult MyMethod(int? MyId)
{
doSomething(MyId);
return View("MyView");
}
但是,當我調試應用程序時,調用該方法時,MyId參數將作為null而不是作為模型中MyId參數的當前值傳遞。 我該怎么做才能正確發送或檢索該值? 謝謝!
在您的路由定義中,我假設參數名為{id}
而不是{MyId}
:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"MyArea_default",
"MyArea/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
因此,嘗試使其更加一致,並相應地調整您的控制器動作參數名稱:
[HttpGet]
public ActionResult MyMethod(int? id)
{
doSomething(id);
return View("MyView");
}
另外,您可能想使用url幫助器,而不是在javascript代碼中對某些url模式進行硬編碼:
window.location.href = '@Url.Action("MyMethod", "SomeControllerName", new { area = "MyArea", id = Model.MyId })';
Url.Content
幫助器用於引用站點中的靜態資源,例如javascript,css和圖像文件。 對於控制器動作,最好使用Url.Action
幫助器方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.