ASP.NET MVC后端消息如何显示在前端asp-validation-summary标签中?
asp-validation-summary Tag Let's break down how to get your backend error message showing up in that validation summary div. The key thing to know here is that ASP.NET Core's asp-validation-summary works natively with ModelState errors—right now your backend is returning a JSON BadRequest, which won't automatically populate the summary. Here are two approaches to fix this:
Approach 1: Use ModelState (Recommended, No Extra JS Needed)
This is the most idiomatic way to handle validation in ASP.NET Core MVC/Razor Pages. Instead of returning a JSON object, add your error to the ModelState and return the original view. The validation summary will automatically pick up the error.
Modify your backend code like this:
[HttpPost] public IActionResult Signup(Signup signup) { var result = DBGetCls.GetList("SELECT * FROM Usertable WHERE Email = '{0}' ", signup.Email); if (result.Count > 0) { // Add a global error (not tied to a specific field) to ModelState ModelState.AddModelError(string.Empty, "Email has been used!"); // Return the signup view with the model, so validation errors render return View(signup); } // Add your registration success logic here (e.g., save to DB) return RedirectToAction("RegistrationSuccess"); }
Why this works:
ModelState.AddModelError(string.Empty, ...)adds a "global" error thatasp-validation-summary="All"will display (since it includes both field-specific and global errors).- When you return the
View(signup), the Razor engine will automatically render all ModelState errors in the validation summary div—no JavaScript required.
Approach 2: Handle AJAX Submission (If You Need JSON Responses)
If you're submitting the form via AJAX and want to keep returning JSON, you'll need to manually inject the error message into the validation summary div with JavaScript.
First, update your frontend to use AJAX submission:
<div id="signup"> <form id="signupForm" asp-action="Signup"> <div asp-validation-summary="All" class="text-danger" id="validationSummary"></div> <div class="field-wrap"> <label asp-for="FullName" class="control-label active highlight">Name :</label> <input asp-for="FullName" class="form-control" /> </div> <!-- Add your other form fields here --> <button type="submit">Sign Up</button> </form> </div> <script> document.getElementById('signupForm').addEventListener('submit', async (e) => { e.preventDefault(); // Stop the default form submission // Collect form data and include the anti-forgery token const formData = new FormData(e.target); const antiForgeryToken = document.querySelector('input[name="__RequestVerificationToken"]').value; try { const response = await fetch(e.target.action, { method: 'POST', body: formData, headers: { 'RequestVerificationToken': antiForgeryToken } }); if (!response.ok) { const error = await response.json(); const summaryDiv = document.getElementById('validationSummary'); // Clear existing errors summaryDiv.innerHTML = ''; // Create a list item for the error (matches the default validation summary markup) const errorList = document.createElement('ul'); const errorItem = document.createElement('li'); errorItem.textContent = error.message; errorList.appendChild(errorItem); summaryDiv.appendChild(errorList); } else { // Redirect to success page or show success message window.location.href = await response.text(); } } catch (err) { console.error('Submission failed:', err); } }); </script>
Notes for this approach:
- Always include the
RequestVerificationTokenin your AJAX request to avoid anti-forgery validation errors. - The JavaScript recreates the default unordered list markup that
asp-validation-summaryuses, so the styling will match your existing form.
内容的提问来源于stack exchange,提问作者Samuel Smith

