Call Action in Controller From View and send parameter

左心房为你撑大大i 提交于 2019-12-24 16:31:23

问题


I am trying to call a method inside a controller in MVC from a javascript action. The javascript action is supposed to invoke this method inside the controller and send some parameters to it.

My Javascript code looks like this:

location.href = '@Url.Content("~/Areas/MyArea/MyMethod/"+Model.MyId)';

My Method is defined as follows:

[HttpGet] 
public ActionResult MyMethod(int? MyId) 
{ 
   doSomething(MyId); 
   return View("MyView"); 
}

However, when i debug the application, when the method is called the MyId parameter is passed as null and not as the current value of the MyId parameter in my model. What can I do to correctly send or retrieve this value? Thanks!


回答1:


In your route definition I suppose that the parameter is called {id} and not {MyId}:

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.MapRoute(
        "MyArea_default",
        "MyArea/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}

So try to be more consistent and adapt your controller action parameter name accordingly:

[HttpGet] 
public ActionResult MyMethod(int? id) 
{ 
    doSomething(id); 
    return View("MyView");
}

Also you probably wanna use url helpers instead of hardcoding some url patterns in your javascript code:

window.location.href = '@Url.Action("MyMethod", "SomeControllerName", new { area = "MyArea", id = Model.MyId })';

The Url.Content helper is used to reference static resources in your site such as javascript, css and image files. For controller actions it's much better to use the Url.Action helper method.



来源:https://stackoverflow.com/questions/24744945/call-action-in-controller-from-view-and-send-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!