c# - 带有数据对象的 ASP.NET Core 重定向

标签 c# asp.net asp.net-core

我正在 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 的参数 valueModel 类的类型,这是一个复杂的类型,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/

相关文章:

c# - Linq to Entity 使用 SelectMany 跳过 OrderBy

c# - ASP.NET Core 2 本地化(ViewLocalizer 不工作)

c# - 有没有办法在实例化从泛型继承的类型时不使用动态?

c# - 如何在 C# 中使用 XPath 获取 SelectedNode 的计数?

c# - 从 Regex 读取捕获组也是 URL 重写规则?可能的?

c# - 如何通过单击链接滚动到页面中的某个位置

.NET Core 2.0 ASP.NET MVC 下载文件和调用文件保存对话框

c# - 如何使 cookie 身份验证方案生成相对登录 url 而不是绝对登录 url?

c# - 如何从 html 源中提取页面上可见的文本?

c# - Entity Framework - 对业务层需求的意见