带有数据对象的ASP.NET Core Redirect

问题描述 投票:0回答:2

我正在控制器中制作一个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获得价值?

c# asp.net asp.net-core
2个回答
3
投票

这是由parameter binding引起的。

value的参数ActionMethod1Model类的类型,这是一个复杂类型,mvc会尝试从http体中绑定它的值,http请求应该是一个POST请求。

但是ActionMethod2返回RedirectToAction结果,浏览器重定向到ActionMethod1GET,并且无法处理由ActionMethod1

答案是将FromQueryAttribute添加到valueActionMethod1参数中,告诉mvc value是从查询字符串绑定的,如下所示:

public IActionResult ActionMethod1([FromQuery]Model value) 
{
    return View(value); ---- debug point (1)
}

现在ActionMethod1将处理GET请求,ActionMethod2可以重定向到它。


1
投票

你想要做的是不可能的。但是有一些解决方法。一种常见的方法是将数据添加到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);
}
© www.soinside.com 2019 - 2024. All rights reserved.