Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Membership:Last Login date of User

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

like image 211
Gayatri Avatar asked Jan 14 '13 15:01

Gayatri


1 Answers

I have solved this way:

  1. 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; }
    }
    
  2. 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);
    } 
    
  3. Then I fetched UserProfiles Like the way bellow:

    public ActionResult Index()
    {
        return View("Index",_db.UserProfiles);
    }
    
  4. 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>
    }
    
like image 50
Babul Mirdha Avatar answered Sep 22 '22 20:09

Babul Mirdha