RedirectToAction在控制器中工作,但不更新视图和URL

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

我有一个用于登录/注册和相关操作的控制器。自从我将用Html助手制作的视图改为测试视图,再到我的UI设计者用html提供的视图,登录后我没有被重定向到索引页面。

起初我认为登录表单没有提交,但在插入一些Console调试代码后,我意识到在控制器中我被重定向到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>

提交后,“重定向到索引”将与之前的行一起打印在控制台中,但我不会被重定向到实际页面。

提前感谢您花时间回答我的问题。

c# asp.net-mvc
3个回答
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 razor helper而不是纯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"/>
}

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); 
}

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.