【问题标题】:How to pass the RedirectUrl from Create action GET to POST如何将 RedirectUrl 从创建操作 GET 传递到 POST
【发布时间】:2018-02-20 05:16:15
【问题描述】:

我正在尝试将RedirectUrl 值从GET 操作传递到POST 操作,该值在使用[Authorize] 修饰的操作时填充。

当我使用TempDataViewBag 时,隐藏的INPUT 元素不会被填充。

/Credential/Create GET:

public IActionResult Create(string returnUrl = null)
{
    // either option has the same effect
    //TempData["returnUrl"] = returnUrl;
    ViewBag.ReturnUrl = returnUrl;

    return View();
}

生成的 HTML:

<input type="hidden" name="returnUrl" />

如果我提供 ViewModel:

public IActionResult Create(string returnUrl = null)
{
    // either option has the same effect
    //TempData["returnUrl"] = returnUrl;
    ViewBag.ReturnUrl = returnUrl;

    CredentialViewModel credential = new CredentialViewModel();
    return View(credential);

}

那么输入包含视图模型的类名:

<input type="hidden" name="returnUrl" value="Foo.Models.ViewModels.CredentialViewModel" />

我做错了什么?

/Credential/Create POST:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("EmailAddress,Password")] CredentialViewModel credential, string returnUrl = null)
{
    // null
    Console.WriteLine(returnUrl);
}

【问题讨论】:

  • 参考它是如何使用 AccountController 和 Login.cshtml 完成的,特别是 Login 方法调用如何将其应用于您的结果。值得注意的是,您的 &lt;input type="hidden" name="returnUrl" value="foo.Models.ViewModels.CredentialViewModel" /&gt; 作为其编码将始终显示该视图模型的整个命名空间,因为您实际上并没有告诉它获取属性,value="@Model.ReturnUrl"(例如)。
  • &lt;input type="hidden" name="returnUrl" value="@ViewBag.ReturnUrl" /&gt; 但不是隐藏输入,您应该将其作为查询字符串值添加到 &lt;form&gt; 元素中。

标签: asp.net-core-mvc


【解决方案1】:

只需使用:

<input type="hidden" name="returnUrl" value="@Context.Request.Query["returnUrl"].SingleOrDefault()" />

那么,你甚至不需要设置ViewBag

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多