Search code examples
asp.net-mvcnugetasp.net-identity

Using Empty template Getting current user Id in asp.net MVC


Guys I'm a bit lost here anyone could help me fix this problem, I cannot display data by current user logged in based from my table,my table will always return empty list, which supposed to display the User and its Subjects.

I'm using empty template in (MVC) I have my own custom authentication + Roles only.I have use Int data type for User Id. Appreciate if you could guide me on what to do with this. Thanks and advance

Nu-get package:Install-Package Microsoft.AspNet.Identity.EntityFramework

Name Space: using Microsoft.AspNet.Identity;

Controller:

[Authorize(Roles = "Admin,Teacher")]
public ActionResult Index()
{
    int userId = User.Identity.GetUserId<int>();
    var subjectTeachers = db.SubjectTeachers.Where(x=>x.UserID==userId);
    return View(subjectTeachers.ToList());
}

Model:

[Key]
public int SubTech { get; set; }
[Display(Name ="SUBJECT")]
public int SubjectID { get; set; }
public virtual Subject Subjects { get; set; }
[Display(Name = "TEACHER")]
public int UserID { get; set; }
public ICollection< User> Users { get; set; }
[Display(Name = "LEVEL")]
public int LevelID { get; set; }
public ICollection< Level> Levels { get; set; }

Target: my table should display the list of subject+level that belongs to the current user logged in. but unfortunately now it is displaying empty list,


Solution

  • Guys after doing some research i found out the way to display the data based on User Current Logged in i just want to share for people who don't know,

    I used empty mvc template then i followed this tutorial link by DotNet awesome thanks to him.http://www.dotnetawesome.com/2015/06/how-to-implement-custom-forms-authentication-in-aspnet-mvc.html.

    I followed all his 4 tutorial , then i add this inside my controller. don't forget to use the following name space.

    using Microsoft.AspNet.Identity;
    
    public ActionResult Index()
        {
    
            if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == true)
            {
                var identity = (System.Web.HttpContext.Current.User as MyProject.MyPrincipal).Identity as MyProject.MyIdentity;
                var demo = db.SubjectTeachers.Where(x => x.UserID == identity.User.UserID).ToList();
                return View(demo);
            };
            return View();
        }