22 Jun 2016
This post gives you step by step instructions for creating a simple login form with a logout button in Umbraco MVC.
using System.ComponentModel.DataAnnotations;
namespace CodeShare.Models
{
public class LoginModel
{
[Display(Name = "Username")]
[Required]
public string Username { get; set; }
[Display(Name = "Password")]
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
}
@inherits Umbraco.Web.Mvc.UmbracoViewPage<CodeShare.Models.LoginModel>
@using Umbraco.Web
@if(!Umbraco.MemberIsLoggedOn())
{
using (Html.BeginUmbracoForm("SubmitLogin", "Member", System.Web.Mvc.FormMethod.Post, new { id="login" }))
{
@Html.AntiForgeryToken()
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username, new { placeholder = "Username" })
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
@Html.ValidationSummary()
<button name="login" type="submit">Login</button>
}
}
else
{
Html.RenderAction("RenderLogout", "Member");
}
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@using Umbraco.Web
@if (Umbraco.MemberIsLoggedOn())
{
using (Html.BeginUmbracoForm("SubmitLogout", "Member", System.Web.Mvc.FormMethod.Post, new { id = "logout" }))
{
@Html.AntiForgeryToken()
var myUser = System.Web.Security.Membership.GetUser();
if (myUser != null)
{
<p><strong>Logged in as</strong> <span>@myUser.UserName</span></p>
<button name="login" type="submit"><span>logout</span> <i class="fa fa-arrow-right"></i></button>
}
}
}
using System.Web.Mvc;
using System.Web.Security;
using Umbraco.Web.Mvc;
using CodeShare.Models;
namespace CodeShare.Controllers
{
public class MemberController : SurfaceController
{
public ActionResult RenderLogin()
{
return PartialView("_Login", new LoginModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SubmitLogin(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.Username, model.Password))
{
FormsAuthentication.SetAuthCookie(model.Username, false);
UrlHelper myHelper = new UrlHelper(HttpContext.Request.RequestContext);
if (myHelper.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return Redirect("/login/");
}
}
else
{
ModelState.AddModelError("", "The username or password provided is incorrect.");
}
}
return CurrentUmbracoPage();
}
public ActionResult RenderLogout()
{
return PartialView("_Logout", null);
}
public ActionResult SubmitLogout()
{
TempData.Clear();
Session.Clear();
FormsAuthentication.SignOut();
return RedirectToCurrentUmbracoPage();
}
}
}
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
Layout = null;
}
@{ Html.RenderAction("RenderLogin", "Member"); }
It's as simple as that. Let me know how you get on with this and if there is anything I need to change.
Follow along with this video to get you started with Umbraco