Javascript 从视图调用控制器中的操作并发送参数
我试图从javascript操作调用MVC中控制器内的方法。javascript操作应该在控制器内调用此方法并向其发送一些参数 我的Javascript代码如下所示:Javascript 从视图调用控制器中的操作并发送参数,javascript,asp.net-mvc,redirect,model-view-controller,Javascript,Asp.net Mvc,Redirect,Model View Controller,我试图从javascript操作调用MVC中控制器内的方法。javascript操作应该在控制器内调用此方法并向其发送一些参数 我的Javascript代码如下所示: location.href = '@Url.Content("~/Areas/MyArea/MyMethod/"+Model.MyId)'; 我的方法定义如下: [HttpGet] public ActionResult MyMethod(int? MyId) { doSomething(MyId); ret
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
helper用于引用站点中的静态资源,如javascript、css和图像文件。对于控制器操作,最好使用Url.Action
helper方法