I am using the simple membership in my asp.net MVC 4 application. How i can get the Last Login date of User. I don't see the date is created in default webpages schema table? Do i need to create the field for the LastLogin date in simple Membership? Thanks
I have solved this way:
I added a LastLogin field to UserProfile Model in UsersContext:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public virtual string UserName { get; set; }
public virtual DateTime? LastLogin { get; set; }
}
I modified the Login Method in AccountController :
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
using (UsersContext db=new UsersContext())
{
UserProfile userProfile = db.UserProfiles.SingleOrDefault(u=>u.UserName==model.UserName);
userProfile.LastLogin = DateTime.Now;
db.Entry(userProfile).State=EntityState.Modified;
db.SaveChanges();
}
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
Then I fetched UserProfiles Like the way bellow:
public ActionResult Index()
{
return View("Index",_db.UserProfiles);
}
Finally, I displayed LastLogin DateTime in Index.cshtml:
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastLogin)
</td>
</tr>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With