How to put an Asp.net Core Web API response in a Bootstrap message on the client side

Jose Daniel Navarro Brito 61 Reputation points
2024-08-22T08:01:05.3+00:00

Good day all:

I'm struggling the following

  1. I have a ASP.NET Core web API that provides User registration as follows
 public async Task<IActionResult> RegisterUser([FromBody] NewUser user)
 {
           
         User appuser = new User()
         {

             UserName = user.Username,
             Email = user.EmailAddress,
             FirstName = user.FirstName,
             LastName = user.LastName,
             Address = user.Address,
             PhoneNumber = user.PhoneNumber,
             CreateAt = DateTime.Today,
             IsBanned = false,
             UnderInvestigation = false
         };
         IdentityResult result = await _userManager.CreateAsync(appuser, user.Password);
         if (result.Succeeded)

            
         return Ok($"User Name {user.Username} was sucessfuly Registered");
         else
         {
             foreach (IdentityError error in result.Errors)
                 return Ok(error.Description);

              //  ModelState.AddModelError("", error.Description);

             return BadRequest(ModelState);
         }


Up to this point my understating is that I don't have to check in the above code whether the ModelState is valid ( just only on the client side right?) . When I run the code in Swagger, all the validation messages pop up e.g Password must have non alphanumeric character, uppercase, if the Username is already taken, etc. All this messages are shown in a response body with a 200 Staus Code.

Back to the client application that consumes the WEB API, I have the following Code

    [HttpPost]
    public async Task<IActionResult> Registration([FromForm] RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var httpClient = _httpClientFactory.CreateClient("HousingWebAPI");
            var body = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
            using (var response = await httpClient.PostAsync("https://localhost:7129/api/Auth/Register?", body))
            {
                /* Checking first if the API is sending a successful StatusCode */
                if (!response.IsSuccessStatusCode)
                {
                    var responseContent = response.Content == null
                        ? "NoContent"
                        : await response.Content.ReadAsStringAsync();
                  
                    TempData["testmsg"] = response;
                    return View("/Views/Registration/Index.cshtml");
                }

                else
                {
                    TempData["testmsg"] = response.Content.ReadAsStringAsync();              
                   
                   return RedirectToAction("Index", "Registration");
                }
            }
        }
        return View("/Views/Registration/Index.cshtml");
        
    }

}

My questions are:

a) How I show to the client via a bootstrap message box all the messages coming from the WEB API?

b) Does the ModelState.Is Valid assures that all the Validations take place in the customer side hence the WEB Api doesn't have to do it?

c) In the event that any developer "forgets"to check the validation, is there any way that the Validation messages from the WEB API can be shown?

d) Is the correct approach to set the response in a TempData and then show it in a Bootstrap message box? if so, how to do it.

Thanking you.

Jose

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,551 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
335 questions
{count} votes

Accepted answer
  1. Ping Ni-MSFT 4,335 Reputation points Microsoft Vendor
    2024-08-23T09:40:08.9+00:00

    Hi @Jose Daniel Navarro Brito,

    a) How I show to the client via a bootstrap message box all the messages coming from the WEB API? Use TempData to pass messages to the view:

    if (!response.IsSuccessStatusCode)
    {
        TempData["ErrorMessage"] = responseContent; // Store the error message
        return View("/Views/Registration/Index.cshtml");
    }
    else
    {
        TempData["SuccessMessage"] = responseContent; // Store the success message
        return RedirectToAction("Index", "Registration");
    }
    

    In your Razor view, add the following code to display the messages:

    @if (TempData["ErrorMessage"] != null)
    {
        <div class="alert alert-danger">
            @TempData["ErrorMessage"]
        </div>
    }
    @if (TempData["SuccessMessage"] != null)
    {
        <div class="alert alert-success">
            @TempData["SuccessMessage"]
        </div>
    }
    

    b) Does the ModelState.Is Valid assures that all the Validations take place in the customer side hence the WEB Api doesn't have to do it?

    ModelState.IsValid checks if the model's data is valid according to the server-side validation rules. It doesn't assure that validation took place on the client-side.

    c) In the event that any developer "forgets"to check the validation, is there any way that the Validation messages from the WEB API can be shown?

    Not sure what do you mean the developer fogets to check, but the server side will always handle the validation.

    d) Is the correct approach to set the response in a TempData and then show it in a Bootstrap message box? if so, how to do it

    Using TempData is a common approach to pass messages from the controller to the view.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 64,826 Reputation points
    2024-08-22T16:13:25.1866667+00:00

    a) just render the bootstrap dialog in the view based on a passed variable:

    @if (!string.IsEmptyOrNull(ViewBag.Message)
    {
    <div class="modal" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Modal title</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <p>@ViewBag.Message</p>
          </div>
          <div class="modal-footer">
          </div>
        </div>
      </div>
    </div>
    } 
    

    b,c) the webapi should validate its parameters. how does it know the caller did it correctly? if the webapi returned the more typical json/xml response it could return detailed error messages and response codes. the binding library fills in the error collection during binding. IsValid just checks that the collection is empty or not.

    d) tempdata is just uses a cookie to pass data to next request. you could also just pass data on the url.

    note: your registration page just redirects to index on any validation error. displaying the validation messages makes more sense. also you do not use the correct view name. read docs.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.