RedirectToAction可在控制器中使用,但不会更新视图和URL

时间:2019-01-21 09:09:48

标签: c# asp.net-mvc

我有一个用于登录/注册和相关操作的控制器。自从将视图从使用Html帮助程序进行测试的视图更改为我的UI设计器随html提供的视图以来,登录后我没有重定向到索引页面。

起初,我以为登录表单没有提交,但是在插入了一些控制台调试代码之后,我意识到在控制器中我将被重定向到Index操作,但是在浏览器中未显示Index视图,并且URL是没有改变。 一些存在相同问题的开发人员说,这是由于AJAX按钮引起的,但我认为我所掌握的观点不尽相同,我也不知道如何确定。

这是我的AccountController代码及其中的操作。我从中删除了多余的代码:

public ActionResult Index()
{
    Console.WriteLine("Redirected To Index");
    return View(model);
}
public ActionResult Login()
{            
    Console.WriteLine("Entered Login Get Action");
    return View();
}

[HttpPost]
public ActionResult Login(LoginViewModel model)
{
    Console.WriteLine("Entered Login Post Action");
    if (ModelState.IsValid)
    {
        Console.WriteLine("Login Redirect Action");
        return RedirectToAction("Index");
    }
    return View(model);
}

这是我的登录视图中正在提交的表单,其中删除了冗余代码:

     <form class="cozy" method="post">
        @Html.TextBoxFor(model => model.Username)
        @Html.PasswordFor(model => model.Password)
        <input type="submit" name="login" value="Login"/>
     </form>

提交后,控制台中将打印“ Redirected To Index”和前几行,但我没有重定向到实际页面。

预先感谢您花时间回答我的问题。

3 个答案:

答案 0 :(得分:0)

我认为您错过了表单上的action属性。

<form class="cozy" method="post" action="@Url.Action("Login","Account")">
        @Html.TextBoxFor(model => model.Username)
        @Html.PasswordFor(model => model.Password)
        <input type="submit" name="login" value="Login"/>
</form>

当您点击表单上的“提交”按钮时,将使用post方法调用Login操作。 َ根据注释中的建议,您可以使用Html.BeginForm剃须刀助手而不是纯HTML代码。

@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "myform", @class = "cozy", enctype = "multipart/form-data" })) {
        @Html.TextBoxFor(model => model.Username)
        @Html.PasswordFor(model => model.Password)
        <input type="submit" name="login" value="Login"/>
}

答案 1 :(得分:0)

请尝试提供视图的完整路径,而不是使用return View(model);

public ActionResult Index()
{
    Console.WriteLine("Redirected To Index");
    return View("add actual path of the view", model); 
    //For Example
    //return View("~/Views/Test/Login.cshtml", model); 
}

答案 2 :(得分:0)

看来问题出在视图中的某些js脚本上,阻止了重定向。我删除了它们,代码再次开始正常工作。然后我再次添加了这些js引用,现在代码可以正常工作了。 我不知道为什么以及为什么以前没有,但这就是我所做的使它再次起作用。