简体   繁体   中英

Call Action in Controller From View and send parameter

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM