Search code examples
asp.net-mvcsimplemembership

Register _LoginPartial if(Request.IsAuthenticated)


I'm hitting a dead end with this one. I'm new to MVC and I see similiar issue appearing on SO, but it does not help. I'm basically trying to set a Register action, and once user is registered _LoginPartial view should indicate that the user is authenticated. From various posts and articles I read I believe I'm missing the element of storing this user to the cookie, but I do not know how to achieve this. I will appreciate any hints.

Controler:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)

WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
int userId = WebSecurity.GetUserId(model.UserName);

string roleName = ConfigurationManager.AppSettings["CustomerRole"];
if (!Roles.RoleExists(roleName)){ Roles.CreateRole(roleName); }
Roles.AddUserToRole(model.UserName, roleName);

var customer = new Customer();
customer.UserId = userId;
customer.Name = model.Name;
customer.PrivateEmail = model.PrivateEmail;

_customerRepo.Add(customer); 
_customerRepo.SaveChanges(); // Customer, Membership, UserProfile added to db, no problems

TempData["Message"] = "User was registered"; // shows
return RedirectToAction("Index", "Home"); // shows 

It seems everything is being saved correctly but the partial view does not see this user anymore... _LoginPartial view

@if(Request.IsAuthenticated) {
<text> user: @Html.ActionLink(User.Identity.Name, "Manage", "Account",routeValues: null, htmlAttributes: new { @class = "username", title = "Change Password" })

@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) 

{@Html.AntiForgeryToken()
<a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>}
</text>
} else {
<ul>
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Register", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}   

Solution

  • You need to call Login() after the SaveChanges();

    It should be something like

    WebSecurity.Login(model.UserName, model.Password, false);

    More information http://www.codeguru.com/csharp/.net/net_asp/mvc/using-simplemembership-in-asp.net-mvc-4.htm