【问题标题】:Asp.net Core, redirect to another view from partial view using form ajax?Asp.net Core,使用表单ajax从部分视图重定向到另一个视图?
【发布时间】:2019-01-18 20:46:33
【问题描述】:

我在 Asp.net core 2.0 中有一个 Partial view,其中包含一个 form ajax

你可以看到Partial View命名为_loginPartial

@model partialView.Models.LoginViewModel

<div id="login">
<form asp-controller="Account" asp-action="Login" id="frmLogin" data-ajax="true" data-ajax-method="POST" data-ajax-update="#frmLogin" data-ajax-mode="Replace">
    <div id="login">

        <div class="form-group">
            <input asp-for="UserName" class="form-control" />
            <span asp-validation-for="UserName"></span>
        </div>

        <div class="form-group">
            <input asp-for="Password" class="form-control" />
            <span asp-validation-for="UserName"></span>
        </div>

        <div class="form-group pull-left ">
            <button type="submit" class="btn btn-success">Submit</button>
        </div>
    </div>
</form>

当我向/Account/Login 提交表单时,一切正常,但登录后我想重定向到另一个Area 中的另一个视图

    [HttpPost]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
        if (ModelState.IsValid)
        {
            //Success Login
            return Redirect("/AdminPanel/Home/Index");
        }
        else
        {
            //if ModelState is invalid

        }

        //if UserName Or Password is incorrect
        return PartialView("_loginpartialView", model);
    }

这里是LoginViewModel

public class LoginViewModel
{
    [Display(Name = "UserName")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Please Enter UserName")]
    public string UserName { get; set; }

    [Display(Name = "Password")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Please Enter Password")]
    [DataType(DataType.Password)]
    public string Password { get; set; }


}

我也使用此代码在index 中显示Partial View

  @Html.Partial("_loginpartialView")

但是有一个问题。成功登录后,新视图替换为Partial view。换句话说,它不会导航到/AdminPanel/Home/Index,新的View 替换为Partial View,在这种情况下如何导航到另一个视图?

【问题讨论】:

  • ajax 的全部意义在于保持在 same 页面中!如果要重定向,请不要使用 ajax。进行正常提交。
  • @StephenMuecke 但是如果ModelState在局部视图中无效,则正常提交无法显示模型错误
  • @StephenMuecke 我不同意。这似乎不是 SPA,因此当有很多更改时重新加载页面可能是可以的。我认为登录可能属于该类别。
  • @AdamSimon,阅读问题 - OP 想要重定向 - 使用 ajax 完全没有意义(并且会降低性能)
  • @StephenMuecke 查看控制器代码,我想说 OP 希望在 登录成功时重定向。否则,他想要显示错误的部分更新。不一定是最好的方法,但对我来说似乎还可以。

标签: asp.net-core asp.net-core-mvc partial-views ajaxform


【解决方案1】:

当您处理 AJAX 回调时,您无法在服务器端进行重定向。这必须在客户端使用 Javascript 进行处理。

检查来自服务器的响应,如果是重定向,则将window.location 设置为接收到的 URL。

【讨论】:

  • 你说我应该使用 jquery ajax 还是 javascript?
  • 完全正确 - 如果您想沿着您描述的道路前进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 2016-04-02
  • 2017-10-30
  • 2020-01-16
相关资源
最近更新 更多