Call Action in Controller From View and send param

2019-08-01 05:35发布

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条回答
2楼-- · 2019-08-01 05:51

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.

查看更多
登录 后发表回答