【问题标题】:ASP.NET MVC Areas - ActionLink and RedirectToActionASP.NET MVC 领域 - ActionLink 和 RedirectToAction
【发布时间】:2013-04-21 01:48:44
【问题描述】:

在 ASP.NET MVC 3 项目中使用区域时,我偶然发现这个问题与 ActionLink 和 RedirectToAction 方法有关。

我在根级别的 AccountController 中添加了以下代码...

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                if (Roles.Provider.IsUserInRole(model.UserName, "Admin"))
                {
                    return RedirectToAction("Index", "Admin", new { area = "Admin" });
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }                        
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

根据当前登录用户所属的角色,我重定向到相应的区域。到目前为止,它工作正常。

管理区如下所示...

在这个区域,我从根目录复制了 _ViewStart.cshtml

注销关于首页等链接无法正常工作,因为它们指向的路线不存在。 p>

我不想在 Areas 文件夹中创建另一个帐户或 Home 控制器。我想使用根目录中的那个。

根据收到的建议,更改 _LogOnPartial.cshtml 代码,如图所示...

@if(Request.IsAuthenticated) {
    <text>Welcome <strong>@User.Identity.Name</strong>!
    [ @Html.ActionLink("Log Off", "LogOff", "Account", new { area = "" }) ]</text>
}
else {
    @:[ @Html.ActionLink("Log On", "LogOn", "Account", new { area = "" }) ]
}

产生以下 URL ...

还是不对。

【问题讨论】:

  • new {area =""} 应该给你根。

标签: asp.net-mvc-3 asp.net-mvc-routing asp.net-mvc-areas


【解决方案1】:

rool 级别的区域将是new { area = "" }。空字符串。

【讨论】:

    【解决方案2】:

    通过更改 _LogOnPartial.cshtml 代码来改进 gdoron 和 Jasen 建议的解决方案,如下工作...

    @if(Request.IsAuthenticated) {
        <text>Welcome <strong>@User.Identity.Name</strong>!
        [ @Html.ActionLink("Log Off", "LogOff", "Account", new { area = "" }, null) ]</text>
    }
    else {
        @:[ @Html.ActionLink("Log On", "LogOn", "Account", new { area = "" }, null) ]
    }
    

    同样,还更改了 _Layout.cshtmlHomeAbout 菜单项的 ActionLink 参数,如下所示...

        <div id="menucontainer">
            <ul id="menu">
                <li>@Html.ActionLink("Home", "Index", "Home", new { area = ""}, null)</li>
                <li>@Html.ActionLink("About", "About", "Home", new { area = "" }, null))</li>
            </ul>
        </div>
    

    链接显示正确并且现在可以使用...

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2011-04-25
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-04
      相关资源
      最近更新 更多