如何在ASP.NET Core MVC中将用户补充信息存储到现有数据库?
Let's break down how to get your profile form data saved to the database step by step. Since the user's email is already stored during signup, we'll focus on updating the existing ApplicationUser record with the new profile details.
Step 1: Fix the Profile View Form
Your current form doesn't bind to the ApplicationUser model, so the controller won't receive the input values. Let's update it to use model binding, set the correct HTTP method, and pre-fill existing user data:
@model ApplicationUser <form asp-action="ProfileView" method="post"> <div class="form-row"> <div class="form-row col-md-6"> <div class="col"> <label for="FirstName">First Name:</label> <input type="text" class="form-control" asp-for="FirstName" placeholder="First name" /> </div> <div class="col col-md-6"> <label for="LastName">Last Name:</label> <input type="text" class="form-control" asp-for="LastName" placeholder="Last name" /> </div> </div> <div class="form-group col-md-6"> <label for="Email">Email</label> <input type="email" class="form-control" asp-for="Email" placeholder="Email" disabled /> </div> </div> <!-- Add remaining profile fields matching your ApplicationUser model --> <div class="form-group col-md-6"> <label for="Address1">Address Line 1:</label> <input type="text" class="form-control" asp-for="Address1" placeholder="Address line 1" /> </div> <div class="form-group col-md-6"> <label for="Address2">Address Line 2:</label> <input type="text" class="form-control" asp-for="Address2" placeholder="Address line 2 (optional)" /> </div> <div class="form-group col-md-6"> <label for="City">City:</label> <input type="text" class="form-control" asp-for="City" placeholder="City" /> </div> <div class="form-group col-md-3"> <label for="ZipCode">Zip Code:</label> <input type="number" class="form-control" asp-for="ZipCode" placeholder="Zip code" /> </div> <button type="submit" class="btn btn-primary mt-3">Save Profile</button> </form>
Key fixes explained:
- Added
@model ApplicationUserat the top to link the form to your user model - Used
asp-actionandmethod="post"to specify the controller action and secure data submission method - The
asp-fortag helper automatically binds inputs to model properties, so the controller receives values correctly - Disabled the email input since it's already stored during signup (prevents unintended changes)
- Added all missing profile fields and a submit button to trigger the save action
Step 2: Update the HomeController to Handle Form Submission
Your current ProfileView only handles GET requests. We'll split it into two handlers: one to show the form with existing user data, and another to process the submission and save changes:
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; public class HomeController : Controller { private readonly UserManager<ApplicationUser> _userManager; // Inject UserManager to access and modify user data (part of ASP.NET Identity) public HomeController(UserManager<ApplicationUser> userManager) { _userManager = userManager; } // GET: Load profile form with current user's data public async Task<IActionResult> ProfileView() { var currentUser = await _userManager.GetUserAsync(User); if (currentUser == null) { // Redirect to login if no user is authenticated return RedirectToAction("Login", "Account"); } // Pass existing user data to pre-fill the form return View(currentUser); } // POST: Process form submission and save profile updates [HttpPost] [ValidateAntiForgeryToken] // Protect against CSRF attacks public async Task<IActionResult> ProfileView(ApplicationUser model) { if (ModelState.IsValid) { var currentUser = await _userManager.GetUserAsync(User); if (currentUser != null) { // Update the user's profile fields with form input currentUser.FirstName = model.FirstName; currentUser.LastName = model.LastName; currentUser.Address1 = model.Address1; currentUser.Address2 = model.Address2; currentUser.City = model.City; currentUser.ZipCode = model.ZipCode; // Save changes to the database var result = await _userManager.UpdateAsync(currentUser); if (result.Succeeded) { TempData["SuccessMessage"] = "Profile updated successfully!"; return RedirectToAction(nameof(ProfileView)); } // Add any update errors to the view for display foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } // Return the view with errors if model validation or update fails return View(model); } }
Key changes explained:
- Injected
UserManager<ApplicationUser>to interact with the user database (built into ASP.NET Identity) - GET handler fetches the logged-in user's data to pre-fill the form
- POST handler validates input, updates the user's record, and handles success/error states
- Added
[ValidateAntiForgeryToken]to secure the form against malicious attacks - Used
TempDatato show a success message after a successful update
Step 3: Fix the DatabaseContext Conflict
Your DataBaseContext has a conflicting Users DbSet that will cause issues with ASP.NET Identity. Since ApplicationUser inherits from IdentityUser, IdentityDbContext<ApplicationUser> already provides a DbSet<ApplicationUser> called Users. Remove the conflicting line:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; public class DataBaseContext : IdentityDbContext<ApplicationUser> { public DataBaseContext(DbContextOptions<DataBaseContext> options) : base(options) { } // Keep your Products DbSet, remove the conflicting Users DbSet public DbSet<Products> Products { get; set; } }
Step 4: Update Database Schema
Since you added new properties to ApplicationUser, you need to create and apply a migration to add these columns to the AspNetUsers table:
- Open the Package Manager Console (or use the .NET CLI)
- Run this command to create a migration:
Add-Migration AddProfileFieldsToApplicationUser - Run this command to apply the migration to your database:
Update-Database
Optional: Add Validation to the Model
Ensure users fill in required fields by adding validation attributes to ApplicationUser:
using System.ComponentModel.DataAnnotations; public class ApplicationUser : IdentityUser { [Required(ErrorMessage = "First name is required")] public string FirstName { get; set; } [Required(ErrorMessage = "Last name is required")] public string LastName { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } [Required(ErrorMessage = "City is required")] public string City { get; set; } [Required(ErrorMessage = "Zip code is required")] public int ZipCode { get; set; } }
内容的提问来源于stack exchange,提问作者Asisk

