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}
:So try to be more consistent and adapt your controller action parameter name accordingly:
Also you probably wanna use url helpers instead of hardcoding some url patterns in your javascript code:
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 theUrl.Action
helper method.