You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC后端消息如何显示在前端asp-validation-summary标签中?

How to Display Backend Messages in the 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:

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 that asp-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 RequestVerificationToken in your AJAX request to avoid anti-forgery validation errors.
  • The JavaScript recreates the default unordered list markup that asp-validation-summary uses, so the styling will match your existing form.

内容的提问来源于stack exchange,提问作者Samuel Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:33:13