我正在尝试从 javascript 操作调用 MVC 中 Controller 内的方法。 javascript 操作应该在 Controller 内部调用此方法并向其发送一些参数。
我的 Javascript 代码如下所示:
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 }
);
}
因此请尽量保持一致并相应地调整您的 Controller 操作参数名称:
[HttpGet]
public ActionResult MyMethod(int? id)
{
doSomething(id);
return View("MyView");
}
此外,您可能想使用 url helpers 而不是在 javascript 代码中对某些 url 模式进行硬编码:
window.location.href = '@Url.Action("MyMethod", "SomeControllerName", new { area = "MyArea", id = Model.MyId })';
Url.Content
帮助程序用于引用站点中的静态资源,例如 javascript、css 和图像文件。对于 Controller 操作,最好使用 Url.Action
辅助方法。
关于javascript - 从 View 调用 Controller 中的操作并发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24744945/