ASP.NET MVC区域 - ActionLink和RedirectToAction

时间:2013-04-21 01:48:45

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

在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.");
        }
    }

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

管理区域如下所示......

enter image description here

在这方面,我从根目录复制了 _ViewStart.cshtml

注销关于主页等的链接不起作用,因为它们指向的路线不存在。

enter image description here

我不想在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 = "" }) ]
}

生成以下网址...

enter image description here

仍然不对。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

通过更改 _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) ]
}

同样,还更改了主页 ActionLink 参数和 _Layout.cshtml 中的关于菜单项,如下所示...

    <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>

链接显示正确并立即正常工作......

enter image description here