Good morning
In my project i have a form for inserting some data in the database and i want this data to be inserted with the current user ID so that latter i can load based on the current user id .
I can get the name, in this case my email, but i want the id.
Do i need to relate my form to the current user id ? or does the framework deal with it ?
How do i get the current session user id into my form ? or simply into my database, no need to load into the form.
.
.
.
@User.Identity.Name -->
.
.
.My Model:
using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
namespace HyperWeb_V3.Models
{
public class Entity
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
[RegularExpression(@"^[a-zA-Z0-9\s]*$",
ErrorMessage = "Only alphanumeric characters and spaces are allowed.")]
public string Title { get; set; }
[Required]
[StringLength(1000)]
public string Description { get; set; }
// Author ID - IMPORTANT
public IdentityUser Author { get; set; }
}
}Maybe i can set it automaticly in the model, would be really greath, or simply get it from somewhere when pressing the submit button.
Best regards
Rui Ruivo

Mohamed Azarudeen ZRank #297 · 8.5K reputationPosted Jul 2, 2023, 3:29 PM EDT
Hi Rui
Here's how you can modify your code to achieve this:
Entitymodel to have anAuthorIdproperty that will store the user's ID:using Microsoft.AspNetCore.Identity; using System.ComponentModel.DataAnnotations; namespace HyperWeb_V3.Models { public class Entity { [Key] public int Id { get; set; } [Required] [StringLength(100, MinimumLength = 3)] [RegularExpression(@"^[a-zA-Z0-9\s]*$", ErrorMessage = "Only alphanumeric characters and spaces are allowed.")] public string Title { get; set; } [Required] [StringLength(1000)] public string Description { get; set; } // Author ID - IMPORTANT public string AuthorId { get; set; } // Store the user's ID as a string. // Define a navigation property for the Author (optional, but can be useful). public IdentityUser Author { get; set; } } }In your controller action responsible for handling the form submission, you can get the current user's ID using
UserManager.GetUserId(User)and set it as theAuthorIdof theEntityobject before saving it to the database.using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Identity; using HyperWeb_V3.Models; using System.Threading.Tasks; namespace HyperWeb_V3.Controllers { public class EntityController : Controller { private readonly UserManager _userManager; private readonly ApplicationDbContext _context; public EntityController(UserManager userManager, ApplicationDbContext context) { _userManager = userManager; _context = context; } [HttpPost] public async Task Create(Entity entity) { if (ModelState.IsValid) { // Get the current user's ID and set it as the AuthorId for the Entity. string currentUserId = _userManager.GetUserId(User); entity.AuthorId = currentUserId; // Save the entity to the database. _context.Entities.Add(entity); await _context.SaveChangesAsync(); // Redirect to a success page or wherever you want to go after creating the entity. return RedirectToAction("Index", "Home"); } // If the model state is not valid, redisplay the form with validation errors. return View(entity); } } }With these modifications, when a user submits the form, the
Createaction in theEntityControllerwill automatically set theAuthorIdproperty to the current user's ID and save the record to the database with the corresponding author information.Rui Ruivo162 reputationPosted Jul 2, 2023, 5:19 PM EDT
Dear sir.
Here is my behind code so far, the problem now is in the modelState, it is always invalide (false):
The field in the database is "(nvarchar(max), not null)", is was, i believe, created from the model.
So far so good, but when the form is submitted the modelstate is false.
How do i solve this ? The userid doesn't come from the form, it is in the server session. That works and i can see the apropriate userId in the variable.
But the modelstate is false.
File: Create.cshtml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using HyperWeb_V3.Data; using HyperWeb_V3.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using System.Security.Claims; namespace HyperWeb_V3.Pages.Entities { [Authorize] public class CreateModel : PageModel { private readonly HyperWeb_V3.Data.ApplicationDbContext _context; private readonly UserManager _userManager; // To get current logged in user public CreateModel(HyperWeb_V3.Data.ApplicationDbContext context, UserManager userManager) { _context = context; _userManager = userManager; // To get current logged in user } public IActionResult OnGet() { return Page(); } [BindProperty] public Entity Entity { get; set; } // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD public async Task OnPostAsync() { // Retrieve the currently logged in user var user = await _userManager.GetUserAsync(User); // To get current logged in user if (user == null) { return Challenge(); } if (!ModelState.IsValid || _context.Entities == null || Entity == null) { foreach (var modelStateVal in ViewData.ModelState.Values) { foreach (var error in modelStateVal.Errors) { var errorMessage = error.ErrorMessage; ModelState.AddModelError("", error.ErrorMessage); } } return Page(); } // Get the current user's ID and set it as the AuthorId for the Entity. string currentUserId = _userManager.GetUserId(User); Entity.AuthorId = currentUserId; _context.Entities.Add(Entity); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } } }Rui Ruivo162 reputationPosted Jul 2, 2023, 5:24 PM EDT
It works very well if i remove the entire modelstate validation.
Is this a potencial solution ?