While using Areas in ASP.NET MVC 3 project, I stumbled across this problem to do with ActionLink and RedirectToAction method.
I added the following code in the AccountController which is at the Root level ...
[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.");
}
}
Based on the Role which the currently logging in User belongs to, I redirect to the appropriate area. It's working correctly up to this point.
The Admin Area looks as follows ...
In this area, I had copied the _ViewStart.cshtml from the root.
The links for Log Off, About, Home etc dont work as the route which they point to doesn't exist.
I don't want to create another Account, or Home controller in the Areas folder. I would like to use the one in the root.
Following the advice received, on changing the _LogOnPartial.cshtml code as shown ...
@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 = "" }) ]
}
produces the following URL ...
which is still not right.