How can I insert the current logged in user in a database using ASP.NET Core

I am trying to insert the current logged in user in a database. I had an idea of making a hidden input text field in the view, taking its value, and inputting it in the database using the asp-for. But it doesn’t seem to work. Can you please tell me what am I doing wrong and if you have any other suggestion on how to fix this in any other way, feel free to tell me.
Thank you in advance <3
This is the view code (P.S I took out some code of the view, I feel as though it is unnecessary for the questions purpose):

<form asp-action="Create">
<div class="form-group">
        <input type="submit" value="Create" class="btn btn-primary" />
        <input type="hidden" value="@UserManager.GetUserName(User)" asp-for="User" readonly>

This is the controller code:

public async Task<IActionResult> Create([Bind("OrderId,Model,Color,Size,Seizure,HatchTrap,User")] ShutterOrders order)
    if (ModelState.IsValid)
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Create));
    return View(order);   


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

if you just want to save in your table order, supposing that user exist and is a string in your table, just do in your controller:

// create a new entry
order myOrder = new order();

// assign values
myOrder.User = User.Identity.Name;
// save other things if necessary...

// add the new data in your table

// save 
await _context.SaveChangesAsync();

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x