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.
.
.
.
.
.
.
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
Rui RuivoPosted Jul 2, 2023, 9:24 PM
It works very well if i remove the entire modelstate validation.
Is this a potencial solution ?
Rui RuivoPosted Jul 2, 2023, 9:19 PM
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
Mohamed Azarudeen ZPosted Jul 2, 2023, 7:29 PM
Hi Rui
Here's how you can modify your code to achieve this:
Entitymodel to have anAuthorIdproperty that will store the user's ID: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.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.