windows.location=url破坏MVC绑定



我正在开发一个javascript函数,该函数应该在获取某些数据后将用户重定向到新页面。

我的例子挫败了这个想法:

var userId = getUserId(e);
var url = baseUrl + "/EditUserRoles/" + userId;
window.location.href = url;

在我的控制器中,我有以下方法:

[HttpGet]
public IActionResult EditUserRoles(int userId)
{
return View(userId);
}

如果在执行的方法中放置断点,但不管javascript 上的上一个值如何,userId始终为0

我在这里做错了什么?

这是因为您的默认路由正在等待id而不是userId

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

3个选项,只选择一个:

1-在MapRoute中将id更改为userId(我不建议这样做(

2-在javascript 中添加userId url参数

var url = baseUrl + "/EditUserRoles/?userId=" + userId;

3-在控制器中将参数名称更改为id

public IActionResult EditUserRoles(int id)

更多信息:https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/asp-net-mvc-routing-overview-cs

最新更新