RedirectToAction不会更改URL

本文关键字:URL RedirectToAction | 更新日期: 2023-09-27 18:20:32

1。我有一个主页(主页/索引)。在这里您可以选择语言。这里的url是:"localhost:xxxx".

2。选择语言后,以下是登录页面(帐户/索引)这里的url是:"localhost:xxxx/Account/Index?language=en-US".

3。当输入数据(用户名/密码)并单击登录按钮时,重定向到用户/索引,但url保留在帐户/Logon 中

我的表单:

<% using (Html.BeginForm("LogOn", "Account")) { %>
<div data-role="fieldcontain" class="ui-hide-label">
  <label for="username">Username:</label>
  <%: Html.TextBoxFor(m => m.Username, new { placeholder = "Username" })%>                      
</div>
<div data-role="fieldcontain" class="ui-hide-label">
  <label for="password">Password:</label>
  <%: Html.PasswordFor(m => m.Password, new { placeholder = "Password" })%>                 
</div>
<fieldset class="ui-grid-a">
  <div class="ui-block-a"><button type="reset" data-theme="d">Reset</button></div>
  <div class="ui-block-b"><button type="submit" data-theme="b">Log On</button></div>
</fieldset>             
<% } %>

账户管理员:

[HandleError]
public class AccountController : Controller
{        
  public ActionResult Index(string language = "es-Es")
  {
    return View();
  }
  [HttpPost]
  public ActionResult LogOn(UserModel user)
  {
    FormsAuthentication.SetAuthCookie(user.Username, false);
    return RedirectToAction("Index", "User");
  }
  public ActionResult LogOff()
  {
    return View();
  }
}

Global.asax:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  routes.MapRoute(
                  "Default", // Route name
                  "{controller}/{action}/{id}", // URL with parameters
                 new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                 );
}

如何使url为:localhost:xxxx/User/Index?

RedirectToAction不会更改URL

在您的登录中使用永久重定向:

[HttpPost]
public ActionResult LogOn(UserModel user)
{
   FormsAuthentication.SetAuthCookie(user.Username, false);
   return RedirectToActionPermanent("Index", "User");
}

Account/Index.cshtml视图中替换:

@using (Html.BeginForm())
{
    ...
}

带有:

@using (Html.BeginForm("LogOn", "Account"))
{
    ...
}

以便在提交表单时调用Account控制器上的LogOn操作,而不是Index操作(它只是返回相同的视图)。

我知道这个问题已经得到了回答,但如果你使用RedirectToRoute,而不是RedirectToAction,会更容易,结果是RedirectToRoute强制更改url。

如果使用jQuery mobile,请确保在目标页面上将data-url属性设置为正确的url:

<div id="my-page" data-role="page" data-url="/myurl">

这就解决了问题。