I'm trying to make a simple Login Page and Storing the logged user using SetAuthCookie but i'm getting an error NullReferenceException was unhandled by user code. I'm still new to this so I'm still not familiar to Cookies Authenticating
I got null error in this line
<h1> @Model.UserName </h1>
Here's my code :
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using logUser.Functions;
using logUser.Models;
namespace logUser.Controllers
{
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
UserInfo employeeUser = new UserInfo();
employeeUser.UserName = User.Identity.Name;
return View();
}
}
}
LoginController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using logUser.Models;
using logUser.Functions;
namespace logUser.Controllers
{
public class LoginController : Controller
{
// GET: Login
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult DoLogin(logUser.Models.UserInfo u)
{
Employee bal = new Employee();
if (bal.IsValidUser(u))
{
FormsAuthentication.SetAuthCookie(u.UserName, true);
return RedirectToAction("Index", "Home");
}
else
{
return View("Login");
}
}
}
}
Login.cshtml
@model logUser.Models.UserInfo
@{
Layout = null;
}
<h2>Login</h2>
<div>
@using (Html.BeginForm("DoLogin", "Login", FormMethod.Post))
{
@Html.LabelFor(c => c.UserName)
@Html.TextBoxFor(x => x.UserName)
<br />
@Html.LabelFor(c => c.Password)
@Html.PasswordFor(x => x.Password)
<br />
<input type="submit" name="BtnSubmit" value="Login" />
}
</div>
Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using logUser.Models;
namespace logUser.Functions
{
public class Employee
{
public bool IsValidUser(UserInfo u)
{
if (u.UserName == "Admin" && u.Password == "Admin")
{
return true;
}
else
{
return false;
}
}
}
}
Index.cshtml
@using logUser.Models
@model UserInfo
@{ var myMessage = "Hello World"; }
<p> Hi! @myMessage </p>
<h1> @Model.UserName </h1>
NOTE : I already configure the Web.config
Thanks