Share via

Client side validation bootstrap modal form Razor Pages

Pablo The Tiger 40 Reputation points
2026-03-30T01:18:44.04+00:00

HelloLast days I got help from @Jack Dang (WICLOUD CORPORATION) and @SurferOnWww on how to show a bootstrap modal form with model (C# class) data. My following issue would be to check data validation on client side. But in the way, I added a list of cars in the html in order to be able to select the Id of the car to show in the form. And in that way I received an ugly surprise: I populate the class member List<Car> cars with the three cars in the OnGet() method and then cars is null in OnGetGetCar() method (previously called OnGetDataResponse) and it throws an Exception and doesn't show the form. But before I added the html car list, I tested the client side validation and it worked fine excepting that the form with the error messages was drawn on html, not the modal form.Would you help me, once again?

Thank you in advance

Pablo

Below I attach in images (it doesn't authorize me to post as code text) the .cshtml.cs (the C#) file

Part 1:

forum 1

Part 2:

forum 2

Below I attach the .cshtml (the HTML / Javascript):

Part 1:

forum 3

Part 2:

forum 4

The _CarPartial.cshtml file:

forum 5

Developer technologies | ASP.NET | ASP.NET Core

Answer accepted by question author
  1. Jack Dang (WICLOUD CORPORATION) 16,195 Reputation points Microsoft External Staff Moderator
    2026-03-30T07:57:58+00:00

    Hi @Pablo The Tiger ,

    Thanks for reaching out.

    From the behavior shown in your screenshot (navigating to /Ajax?handler=Edit and rendering the form as a full page), the issue here is that the form submission is not being handled via AJAX, but instead is falling back to a normal HTTP POST.

    This happens because the submit handler in your JavaScript is bound to a different form ID than the one actually rendered in your partial view.

    In _CarPartial.cshtml, your form is defined as:

    <form method="post" id="myForm" asp-page-handler="Edit">
    

    But in Ajax.cshtml, your script is listening for:

    $(document).on("submit", "#carForm", function (e)
    

    Since these IDs don’t match, the submit event is never intercepted, meaning e.preventDefault() is not executed. As a result, the browser performs a normal form submission to ?handler=Edit.

    Because your handler returns a partial view:

    return Partial("_CarPartial", car);
    

    …the browser simply renders that partial as a standalone page, which explains the “unstyled” result you’re seeing instead of the content being injected back into the modal.

    You just need to align the form ID and the JavaScript selector.

    Option 1 (recommended): update the form ID

    <form method="post" id="carForm" asp-page-handler="Edit">
    

    Option 2: or update the JavaScript

    $(document).on("submit", "#myForm", function (e)
    

    Once they match, the submit will be properly intercepted and handled via AJAX. That means:

    • On validation failure, the returned HTML will be injected back into the modal
    • On success, the modal will close and your page can refresh as expected

    Hope this helps! If my answer was helpful, I would greatly appreciate it if you could follow the instructions here so others with the same problem can benefit as well.


2 additional answers

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  2. Q&A Assist
    2026-03-30T01:19:12.22+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    cars is null in OnGetGetCar because Razor Pages creates a new PageModel instance for every request. The list is only populated in OnGet, so the AJAX OnGetGetCar request runs on a fresh instance where cars has never been initialized.

    To fix the null list and get client-side validation working inside the Bootstrap modal, apply these changes:

    1. Initialize cars on every request
    public class AjaxModel : PageModel
    {
        [BindProperty]
        public Car? car { get; set; }
    
        [BindProperty]
        public List<Car>? cars { get; set; }
    
        private static readonly List<Car> _seedCars = new()
        {
            new Car(1, "Type 1", 2022, "Ranger"),
            new Car(2, "Type 2", 2019, "All terrain"),
            new Car(3, "Type 3", 2025, "4x4")
        };
    
        public void OnGet()
        {
            cars = _seedCars.ToList();
        }
    
        public IActionResult OnGetGetCar(int id)
        {
            cars = _seedCars.ToList();   // ensure list is populated
    
            var car = cars.FirstOrDefault(c => c.Id == id);
            if (car == null)
                return NotFound();
    
            return Partial("_CarPartial", car);
        }
    
        public IActionResult OnPostEdit(Car car)
        {
            cars = _seedCars.ToList();   // if needed for lookups
    
            if (!ModelState.IsValid)
            {
                // return the partial so validation messages render in the modal
                return Partial("_CarPartial", car);
            }
    
            var existingCar = cars.FirstOrDefault(c => c.Id == car.Id);
            if (existingCar == null)
                return NotFound();
    
            existingCar.CarType = car.CarType;
            existingCar.Year    = car.Year;
            existingCar.Model   = car.Model;
    
            return new JsonResult(new { success = true });
        }
    }
    

    The key point is that cars must be set inside OnGetGetCar (and any other handler that needs it), not only in OnGet.

    1. Ensure client-side validation scripts are loaded

    In the main page (for example _Layout.cshtml or the Razor Page), reference the validation scripts so the partial’s asp-validation-for spans work inside the modal:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.js"></script>
    

    These scripts enable unobtrusive client-side validation based on the data- attributes generated from the Car model’s data annotations.

    1. Re-parse validation when the partial is injected

    Because the form is loaded dynamically into the modal, re-parse the injected HTML so jQuery Unobtrusive Validation wires up the rules:

    const html = await response.text();
    $("#grid").html(html);
    $.validator.unobtrusive.parse("#grid");
    
    const modal = new bootstrap.Modal(document.getElementById("exampleModal"));
    modal.show();
    
    1. Keep the existing AJAX submit pattern

    The current pattern is correct: when OnPostEdit returns the partial view (validation failed), replace the modal content and call $.validator.unobtrusive.parse("#grid") again; when it returns JSON { success: true }, hide the modal and refresh the table.

    With cars initialized in each handler and unobtrusive validation re-parsed after injecting the partial, the modal form will show validation errors client-side instead of rendering a full page.


    References:

    0 comments No comments

Your answer

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