ASP.NET Identity中添加用户邮编与地址更新页面的技术咨询
Hey there! Let's break down your questions one by one since you're working with ASP.NET Identity's Razor Pages setup.
1. Where's the controller for adding views in the Areas/Identity/Pages directory?
Quick clarification: ASP.NET Identity uses Razor Pages here, not traditional MVC controllers. Each .cshtml file in the Areas/Identity/Pages folder has a corresponding code-behind file (.cshtml.cs) that acts as the "controller" for that page. Razor Pages are page-focused, so all logic for handling GET/POST requests lives right in that code-behind file—no separate controller class is needed.
For example, the Register.cshtml page you modified earlier uses Register.cshtml.cs (with the OnPostAsync method) to handle form submissions and user creation. The same pattern applies to any new page you add here.
2. How to create a new page to update PostalCode and Address fields?
Let's walk through a step-by-step implementation:
Step 1: Ensure your ApplicationUser includes the required fields
First, confirm your ApplicationUser class (usually in Models/IdentityModels.cs or similar) has the PostalCode and Address properties. If not, add them:
public class ApplicationUser : IdentityUser { // Your existing properties (FirstName, LastName, etc.) public string PostalCode { get; set; } public string Address { get; set; } }
Run these commands in the Package Manager Console to update the AspNetUsers table:
Add-Migration AddPostalCodeAndAddressFields Update-Database
Step 2: Create the new Razor Page
In the Areas/Identity/Pages directory, create a subfolder like Account (to keep things organized) and add a new Razor Page named UpdateProfile.cshtml (right-click the folder → Add → Razor Page → Empty).
Step 3: Set up the code-behind file (UpdateProfile.cshtml.cs)
This file handles loading the current user's data and processing the update. Replace the default code with this:
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; namespace YourProjectName.Areas.Identity.Pages.Account { [Authorize] // Ensure only logged-in users can access this page public class UpdateProfileModel : PageModel { private readonly UserManager<ApplicationUser> _userManager; public UpdateProfileModel(UserManager<ApplicationUser> userManager) { _userManager = userManager; } [BindProperty] public InputModel Input { get; set; } public class InputModel { [Display(Name = "Postal Code")] [StringLength(20, ErrorMessage = "The Postal Code can't exceed 20 characters.")] public string PostalCode { get; set; } [Display(Name = "Address")] [StringLength(500, ErrorMessage = "The Address can't exceed 500 characters.")] public string Address { get; set; } } public async Task<IActionResult> OnGetAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Couldn't load user with ID '{_userManager.GetUserId(User)}'."); } // Populate form with existing user data Input = new InputModel { PostalCode = user.PostalCode, Address = user.Address }; return Page(); } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Couldn't load user with ID '{_userManager.GetUserId(User)}'."); } // Update fields only if they've changed (optional but efficient) if (Input.PostalCode != user.PostalCode) { user.PostalCode = Input.PostalCode; } if (Input.Address != user.Address) { user.Address = Input.Address; } var updateResult = await _userManager.UpdateAsync(user); if (updateResult.Succeeded) { TempData["SuccessMessage"] = "Your profile has been updated successfully!"; return RedirectToPage(); } // Add any errors to the model state foreach (var error in updateResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return Page(); } } }
Note: Replace YourProjectName with your actual project's namespace.
Step 4: Build the view (UpdateProfile.cshtml)
Replace the default view code with this to render the form (matching your existing form-floating style):
@page @model YourProjectName.Areas.Identity.Pages.Account.UpdateProfileModel @{ ViewData["Title"] = "Update Your Profile"; } <h1>@ViewData["Title"]</h1> <div class="row"> <div class="col-md-4"> <form method="post"> <div asp-validation-summary="All" class="text-danger mb-3"></div> @if (TempData["SuccessMessage"] != null) { <div class="alert alert-success mb-3">@TempData["SuccessMessage"]</div> } <div class="form-floating mb-3"> <input asp-for="Input.PostalCode" class="form-control" /> <label asp-for="Input.PostalCode"></label> <span asp-validation-for="Input.PostalCode" class="text-danger"></span> </div> <div class="form-floating mb-3"> <textarea asp-for="Input.Address" class="form-control" rows="4"></textarea> <label asp-for="Input.Address"></label> <span asp-validation-for="Input.Address" class="text-danger"></span> </div> <button type="submit" class="w-100 btn btn-lg btn-primary">Save Changes</button> </form> </div> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
Step 5: Test the page
You can now navigate to /Identity/Account/UpdateProfile (once logged in) to see and use the form. The page will load your existing postal code/address, validate submissions, and update the AspNetUsers table when you click "Save Changes".
内容的提问来源于stack exchange,提问作者Tamil Cantroz

