How to return only the data ref. to logged in user

0

I have a table that returns the following data from a SQL Server database:

  • Initial KM;
  • Final KM;
  • Liters;
  • Value R $.

ButIwouldliketoonlyreturntherefvalues.totheloggedinuser.

InthetableintheDB,Ihaveacolumnthatsavestheusername(Note:Iknowthenameisnotthebest,buttheuserID,butatthemomentwearegoingtoworkwithnames.)

Controller :

public class CombustivelController : Controller
{
    private CombustiveisContext db = new CombustiveisContext();

    // GET: Combustivel
    public async Task<ActionResult> Index()
    {
        return View(await db.CombustivelModels.ToListAsync());
    }

    .
    .
    .
    .
}

How could I make this query?

    
asked by anonymous 01.12.2016 / 10:52

1 answer

2

If you want to get the username logged in, just use the following code:

public class CombustivelController : Controller
{
    private CombustiveisContext db = new CombustiveisContext();

    // GET: Combustivel
    public async Task<ActionResult> Index()
    {
        var name = User.Identity.Name;
        return View(await db.CombustivelModels.Where(c => c.UserId == name).ToListAsync());
    }
}

However, this is not a very apt approach. I recommend saving the ID of the user correctly.

To get the ID of the logged in user, just use this code:

using Microsoft.AspNet.Identity;
 ...
 public class CombustivelController : Controller
    {
        private CombustiveisContext db = new CombustiveisContext();

        // GET: Combustivel
        public async Task<ActionResult> Index()
        {
            var userId= User.Identity.GetUserId();
            return View(await db.CombustivelModels.Where(c => c.UserId == userId).ToListAsync());
        }
    }
    
01.12.2016 / 12:07