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

Asked

Viewed 415 times

0

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

  • INITIAL KM;
  • KM Final;
  • Liters;
  • R-value$.

inserir a descrição da imagem aqui

However I would like to return only the values ref. to the logged in user.

In the table in BD, I have a column that saves the user name (Note: I know that the name is not the best way, but the user ID, but at the moment we will work with names).

inserir a descrição da imagem aqui

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 do this consultation?

  • what is "logged in user"? It is the SQL Server user or the application has an internal user table?

  • @User Josédiz logged in via Identity, user logged in the page.

  • Now the context is clear ("user logged in to the page"). It is that in the description there is only "logged in user" and the topic has the sql-server tag, which induced me to suggest the internal SQL Server functions that provide user/logon information.

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 appropriate approach. I advise saving the ID user correctly.

To obtain the ID 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());
        }
    }
  • Thanks for explaining how to get the user id, but my doubt is how to load the list, bringing only the user data logged in.

  • 1

    @Thomaserichpimentel Notice I added one Where() in your consultation. In this Where() i return data only from the logged in user: db.CombustivelModels.Where(c => c.UserId == userId)

  • Perfect Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.