我正在控制器中制作一个Action方法,如下所示。
在模型中
public class Model
{
public string modelStr { get; set; }
}
在控制器中
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)debuger不停止在debug point (2)
和debug point (1)
value
没有价值,即value.modelStr == null
。
debug point (1)
的价值如何从ActionMethod2
获得价值?
这是由parameter binding引起的。
value
的参数ActionMethod1
是Model
类的类型,这是一个复杂类型,mvc会尝试从http体中绑定它的值,http请求应该是一个POST请求。
但是ActionMethod2
返回RedirectToAction
结果,浏览器重定向到ActionMethod1
与GET
,并且无法处理由ActionMethod1
。
答案是将FromQueryAttribute
添加到value
的ActionMethod1
参数中,告诉mvc value
是从查询字符串绑定的,如下所示:
public IActionResult ActionMethod1([FromQuery]Model value)
{
return View(value); ---- debug point (1)
}
现在ActionMethod1
将处理GET请求,ActionMethod2
可以重定向到它。
你想要做的是不可能的。但是有一些解决方法。一种常见的方法是将数据添加到TempData字典并在另一种方法中检索它:
public IActionResult ActionMethod1()
{
var value = (Model)TempData["model"];
return View(value);
}
public IActionResult ActionMethod2(int pageKind)
{
Model temp = new Model();
if (pageKind == 1)
{
temp.modelStr = "Hi ASP.NET Core";
}
else
{
temp.modelStr = "error!";
}
TempData["model"] = temp;
return RedirectToAction("ActionMethod1");
}
或者,您确定甚至需要实际重定向用户吗?您可以随时直接调用该方法:
public IActionResult ActionMethod1(Model value)
{
return View(value);
}
public IActionResult ActionMethod2(int pageKind)
{
Model temp = new Model();
if (pageKind == 1)
{
temp.modelStr = "Hi ASP.NET Core";
}
else
{
temp.modelStr = "error!";
}
return ActionMethod1(temp);
}