0

I am new to ASP.NET Core MVC. I have to make a project in which multiple user accounts creates and each user creates his own Todo with CRUD operation. Each user should be able to see his/her own Todo listing page.

For this, I used identity framework. I did this work until now

How to add tables and relations to generated ASP.NET Core MVC Identity database?

My code shows all Todo listing in every user login. Please guide me how each user see and operate his own Todo.

This is my code:

public async Task<IActionResult> Index()
{
    return View(await _context.Activitiess.ToListAsync());
}

[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Description")] Activities activities)
{
        if (ModelState.IsValid)
        {
            _context.Add(activities);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        return View(activities);
}

[Authorize]        
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Description")] Activities activities)
{
        if (id != activities.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(activities);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ActivitiesExists(activities.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return RedirectToAction(nameof(Index));
        }

        return View(activities);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

You should add a validation that the current UserId of the logged in user is matching the id of the user that you are trying to add/edit a ToDo. I am guessing that the Index Action is the one that you want to show the user his current todo list. So get the currently logged userId by doing this:

var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier)

Then from the dbContext or if you have a service just find that user with his todo list and show the todo list. I recommend using atleat a service layer with form models, because your controller would get overcrowded with code and is good practice that the controller doesn't "know" about the dbcontext. So you do something like this:

var activities = _context.Users.Where(x => x.Id == userId)
.Select(x => new ActivitiesViewModel()
{
 Item = x.Item,
 and so on
})
.ToList();

Pass those activities to your View.

AchoVasilev
  • 454
  • 5
  • 15