Samuel Smith
Samuel Smith

Reputation: 149

display error message on front-end asp.net mvc

How do I display a message on a div <div asp-validation-summary="All" class="text-danger"></div> when I am sending a message from the back-end?

[HttpPost]
        public IActionResult Signup(Signup signup)
        {
                var result = DBGetCls.GetList("SELECT * FROM Usertable WHERE Email = '{0}' ", signup.Email);
                if (result.Count > 0)
                {
                    object notFound = new { message = "Email has been used!" };
                    return BadRequest(notFound);
                }

So my form would look like this:

<div id="signup">
    <form asp-action="Signup">

        <div asp-validation-summary="All" class="text-danger"></div>

        <div class="field-wrap">
            <label asp-for="FullName" class="control-label active highlight">Name :</label>
            <input asp-for="FullName" class="form-control" />
        </div>
         .
         .

Upvotes: 1

Views: 1262

Answers (1)

Georg Patscheider
Georg Patscheider

Reputation: 9463

In your frontend MVC controller, you can add errors to the model state. These will be rendered in the validation summary. So when the backend answers with BadRequest, add an error manually.

ModelState.AddModelError("PropertyNameInViewModelToBeHighlighted", 
    "Error message to be shown in validation summary");

Some teams also build custom infrastructure to wrap the backend calls, catch any errors, extract the error message, and add it to the ModelState automatically.

See also What is the ModelState?

Upvotes: 1

Related Questions