asp.net-corevalidationasp.net-core-mvcbootstrap-modal

How to trigger error message when client-side validation on modal create in ASP.NET Core MVC


I have trouble in display basic error message despite the validation is working (as in preventing the item to be created with invalid value). Here are the code

This is my Views (Index.cshtml)

@model PickYaKoi.Models.KoiViewModel

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Table here -->


<!-- Modal -->
<div class="modal fade" id="createKoiModal" tabindex="-1" aria-labelledby="createKoiModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="createForm" method="post">
                <div class="modal-header">
                    <h5 class="modal-title" id="createKoiModalLabel">Create new Koi</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <div class="border p-3 mt-4 modal-body">
                
                    <div class="mb-3">
                        <label asp-for="Koi.Name" for="Name" class="p-0">Name</label>
                        <input asp-for="Koi.Name" id="Name" type="text" name="Name" class="form-control" />
                        <span asp-validation-for="Koi.Name" class="text-danger"></span>
                    </div>
                    <div class="mb-3">
                        <label asp-for="Koi.Description" for="Description" class="p-0">Description</label>
                        <input asp-for="Koi.Description" id="Description" name="Description" type="text" class="form-control" />
                        <span asp-validation-for="Koi.Description" class="text-danger"></span>
                    </div>
                    <div class="mb-3">
                        <label asp-for="Koi.Amount" for="Amount" class="p-0">Amount Left</label>
                        <input asp-for="Koi.Amount" id="Amount" type="text" name="Amount" class="form-control" />
                        <span asp-validation-for="Koi.Amount" class="text-danger"></span>
                    </div>
                    <div class="mb-3">
                        <label asp-for="Koi.Status" for="Status" class="p-0">Choose Status</label>
                        <select asp-for="Koi.Status" id="Status" name="Status" class="form-control">
                            <option value="Available">Available</option>
                            <option value="Unavailable">Unavailable</option>
                        </select>
                    </div>
               
                        <div class="modal-footer">
                            <a href="#" class="btn btn-primary form-control" id="btnSave"> Create </a>
                            <button class="btn btn-outline-secondary form-control" id="btnCancel" data-bs-dismiss="modal">Go back</button>
                        </div>
                    
                </div>
            </form>
        </div>
    </div>
</div>


This is my models

public class Koi
{
    [Key]
    public int Id { get; set; }

    [Required]
    [DisplayName("Koi Name")]
    public string Name { get; set; }

    [DisplayName("Koi Description")]
    [MaxLength(255)]
    public string Description { get; set; }

    [Required]
    [Range(0, 9999)]
    public int Amount { get; set; }

    [Required]
    public availableStatus Status { get; set; }

}

I tried to call partial name="_ValidationScriptsPartial" which help enable those client-side validation at the bottom of Index.cshtml. This usually work on a basic non-modal form; however, I am working with modal right now

@section Scripts {
    @{
        <partial name="_ValidationScriptsPartial" />
        
    }

}

In _ValidationScriptsPartial.cshtml has:

<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

Edit: So after testing around, I might found the original problem that preventing the error message from appearing in the first place. By only using Koi object as only model, it's able to display that message. However I want to use KoiViewModel, which contains both Koi and List object, for both Create Modal and Display Table. Once I put that as a Model for that View, The error messsage no longer display as usual.


Solution

  • You should add asp-action to the form and Your ask-for and asp-validation-for should write only the property. Your create button can write like this <input type="submit" value="Create" class="btn btn-primary" />

    I copy your code and complete the Action to write an example .

    1.KoiViewModel.cs. If the class name and file name are inconsistent ,I have an error reported.So I make them the same

    public class KoiViewModel
    {
        [Key]
        public int Id { get; set; }
     
        [Required]
        [DisplayName("Koi Name")]
        public string Name { get; set; }
     
        [DisplayName("Koi Description")]
        [MaxLength(255)]
        public string Description { get; set; }
     
        [Required]
        [Range(0, 9999)]
        public int Amount { get; set; }
    }
    
    1. I use the scaffolding tool to produce Create, Read, Update, and Delete (CRUD) pages for the movie model. you can learn more from this website:https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-8.0&tabs=visual-studio

    2. write the Action. The first (HTTP GET) CreateModal action method displays the initial Create form. The second ([HttpPost]) version handles the form post.The second CreateModal method (The [HttpPost] version) calls ModelState.IsValid to check whether the createKoiModal has any validation errors. you can learn more from this website:https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation?view=aspnetcore-8.0

    controller.cs:

    public IActionResult CreateModal()
    {
         return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> CreateModal([Bind("Id,Name,Description,Amount")] KoiViewModel koiViewModel)
    {
         if (ModelState.IsValid)
         {
             _context.Add(koiViewModel);
             await _context.SaveChangesAsync();
             return RedirectToAction(nameof(Index));
         }
         return View(koiViewModel);
    }
    
    1. .cshtml

       @model ExceptionDemo.Models.KoiViewModel
           <!-- Bootstrap JS -->
           <script src=https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
      
           <!-- jQuery -->
           <script src=https://code.jquery.com/jquery-3.6.0.min.js></script>
      
       <!-- Table here -->
      
      
       <!-- Modal -->
      @*<div class="modal" id="createKoiModal" tabindex="-1" aria-labelledby="createKoiModalLabel" >
           <div class="modal-dialog">
               <div class="modal-content"> *@
                 <form id="createForm" method="post" asp-action="CreateModal">
                       <div class="modal-header">
                           <h5 class="modal-title" id="createKoiModalLabel">Create new Koi</h5>
                           <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                       </div>
      
                       <div class="border p-3 mt-4 modal-body">
      
                           <div class="mb-3">
                               <label asp-for="Name" for="Name" class="p-0">Name</label>
                               <input asp-for="Name" id="Name" type="text" name="Name" class="form-control" />
                               <span asp-validation-for="Name" class="text-danger"></span>
                           </div>
                           <div class="mb-3">
                               <label asp-for="Description" for="Description" class="p-0">Description</label>
                               <input asp-for="Description" id="Description" name="Description" type="text" class="form-control" />
                               <span asp-validation-for="Description" class="text-danger"></span>
                           </div>
      
      
                               <div class="modal-footer">
                                   <input type="submit" value="Create" class="btn btn-primary" />
                                   @* <a href="#" class="btn btn-primary form-control" id="btnSave"> Create </a> *@
                                   <button class="btn btn-outline-secondary form-control" id="btnCancel" data-bs-dismiss="modal">Go back</button>
                               </div>
      
                       </div>
                   </form>
              </div>
           @*</div>
       </div> *@
      

    The result is :

    enter image description here