我正在 Controller 中创建一个 Action 方法,如下所示。
在模型中
public class Model
{
public string modelStr { get; set; }
}
在 Controller 中
public IActionResult ActionMethod1(Model value)
{
return View(value); ---- debug point (1)
}
public IActionResult ActionMethod2(int pageKind)
{
Model temp = new Model();
if (pageKind == 1)
{
temp.modelStr = "Hi ASP.NET Core";
}
else
{
temp.modelStr = "error!";
}
return RedirectToAction("ActionMethod1", temp); ---- debug point (2)
}
然后我在浏览器中使用 /Controller/ActionMethod2
访问 ActionMethod2。
我预计 /Controller/ActionMethod1
将被调用,其模型 value
具有由 ActionMethod2
发送的值。
但是如果我调试它,1) 调试器不会在 调试点 (2)
和 调试点 (1)
值
处停止> 没有值,即 value.modelStr == null
。
调试点(1)
的值如何从ActionMethod2
获取值?
最佳答案
这是由 parameter binding 引起的.
ActionMethod1
的参数 value
是 Model
类的类型,这是一个复杂的类型,mvc 会尝试从 http 绑定(bind)它的值body,http请求应该是POST请求。
但是ActionMethod2
返回一个RedirectToAction
结果,浏览器用GET
重定向到ActionMethod1
,无法处理通过 ActionMethod1
。
答案是在ActionMethod1
的参数value
中添加FromQueryAttribute
,告诉mvc value
是bind from查询字符串,像这样:
public IActionResult ActionMethod1([FromQuery]Model value)
{
return View(value); ---- debug point (1)
}
现在 ActionMethod1
将处理 GET 请求,ActionMethod2
可以重定向到它。
关于c# - 带有数据对象的 ASP.NET Core 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48534300/