Share via

Fill bootstrap modal with data object's fields from AJAX and then send data to server

Pablo The Tiger 186 Reputation points
2026-03-20T13:20:28.3933333+00:00

Hello,

Last time I got help to read data object from AJAX and show its fields in the html. Now I would like to fill the bootstrap modal with the fields. I tried with asp-for but it didn't work. Algo I'd like to send the edited values to server.

I attach the cshtml y the .cs in images because if I put them as text it doesn't authorize me to post.

I will appreciate your help.

Pablo

forum 2

forum 1

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments

3 answers

Sort by: Most helpful
  1. Jack Dang (WICLOUD CORPORATION) 16,435 Reputation points Microsoft External Staff Moderator
    2026-03-23T04:24:12.26+00:00

    Hi @Pablo The Tiger ,

    Thanks for reaching out.

    The thing to be aware of is that asp-for only works when Razor renders the HTML on the server. In your current setup, the modal is already rendered first, and then the car data arrives later via AJAX, so those inputs won’t be populated automatically.

    Since you’re already returning a Partial View from OnGetDataResponse, the appropriate approach is to let the server render the form inside that Partial View, inject the HTML into the modal, and then post the edited values back using standard Razor Pages model binding.

    You might arrange it like this:

    1. Put the form in _CarPartial.cshtml:

    Make the partial strongly typed and render the fields there. Place _CarPartial.cshtml in the same folder as Ajax.cshtml, or under Pages/Shared so Razor can locate it.

    @model RazorPages.Pages.Car
    
    <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">Edit car</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
    </div>
    
    <form method="post" asp-page-handler="SaveCar">
        @Html.AntiForgeryToken()
    
        <div class="modal-body">
            <input asp-for="Id" type="hidden" />
    
            <div class="mb-3">
                <label asp-for="CarType" class="col-form-label"></label>
                <input asp-for="CarType" class="form-control" />
                <span asp-validation-for="CarType" class="text-danger"></span>
            </div>
    
            <div class="mb-3">
                <label asp-for="Year" class="col-form-label"></label>
                <input asp-for="Year" class="form-control" />
                <span asp-validation-for="Year" class="text-danger"></span>
            </div>
    
            <div class="mb-3">
                <label asp-for="Model" class="col-form-label"></label>
                <input asp-for="Model" class="form-control" />
                <span asp-validation-for="Model" class="text-danger"></span>
            </div>
        </div>
    
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
    </form>
    
    1. Keep the modal as a container in Ajax.cshtml:

    Remove the hardcoded inputs and leave a placeholder for the partial. Accessibility attributes are included.

    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content" id="grid">
                <!-- Partial will be injected here -->
            </div>
        </div>
    </div>
    
    1. Load the partial into the modal and then show it:

    Update your script to fetch the partial HTML and inject it:

    document.getElementById("load").addEventListener("click", async () => {
        const url = '@Url.Page("Ajax", "DataResponse")' + '?id=1';
    
        const response = await fetch(url);
        if (response.ok) {
            const html = await response.text();
            document.getElementById("grid").innerHTML = html;
    
            const modal = new bootstrap.Modal(document.getElementById("exampleModal"));
            modal.show();
        }
    });
    
    1. Handle the post in the PageModel:

    To ensure the field names bind correctly, accept the Car object directly as a handler parameter:

    public IActionResult OnPostSaveCar(Car car)
    {
        if (!ModelState.IsValid)
        {
            // Note: returning Page() will close the modal.
            // For production, consider reopening the modal or using AJAX to submit and show validation errors.
            return Page();
        }
    
        // Save car.Id, car.CarType, car.Year, car.Model here
    
        return RedirectToPage();
    }
    

    Note: The code snippets above are simplified examples for illustration. You may need to adjust model names, namespaces, handlers, or validation setup to fit your project.

    If you found my response helpful or informative in any way, I would greatly appreciate it if you could follow this guidance provide feedback. 

    Thank you.

    1 person found this answer helpful.

  2. SurferOnWww 5,926 Reputation points
    2026-03-21T02:20:23.1+00:00

    I understand that your code shown in your question uses the partial view as I suggested in your previous question and the html returned by the partial view is rendered in the div tag <div id="grid"></div> on button click.

    Please consider the followings:

    (1) Delete the div tag <div id="grid"></div>.

    (2) Delete the html <form> ... </form> in the modal entirely. Have the partial view take care of rendering the html code.

    (3) Add id="grid"to the <div class="modal body"> in the modal.

    (4) Write JavaScript code to show the modal after document.getElementById('grid').innerHTML = html;

    Shown below is sample:

    .cshtml.cs

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorPages.Pages
    {
        public class AjaxModel : PageModel
        {
            public void OnGet()
            {
            }
            
            public IActionResult OnGetDataResponse(int? id)
            {
                if (id == null)
                {
                    return NotFound();
                }
    
                var cars = new List<Car>
                {
                    new Car { Id = 1, Brand = "Ford", Year = 2022, Price = 20000 },
                    new Car { Id = 2, Brand = "Renault", Year = 2019, Price = 25000 },
                    new Car { Id = 3, Brand = "Audi", Year = 2025, Price = 40000 }
                };
    
                // returns default(Car) if not found. default(T) is null for reference types
                var car = cars.FirstOrDefault(c => c.Id == id);
                if (car == null)
                {
                    return NotFound();
                }
    
                return Partial("_CarPartial", car);
            }
        }
    
        public class Car
        {
            // Add id
            public int Id { get; set; }
            public string? Brand { get; set; }
            public int Year { get; set; }
            public int Price { get; set; }
        }
    }
    

    .cshtml

    enter image description here

    _CarPartial.schtml (Partial view)

    @model RazorPages.Pages.Car
    <label asp-for="Brand" class="form-label">Brand:</label>
    <input type="text" asp-for="Brand" class="form-control" />
    <label asp-for="Year" class="form-label">Year:</label>
    <input type="text" asp-for="Year" class="form-control" />
    <label asp-for="Price" class="form-label">Price:</label>
    <input type="text" asp-for="Price" class="form-control" />
    

    Result:

    enter image description here

    1 person found this answer helpful.

  3. Q&A Assist
    2026-03-20T13:20:52.7133333+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    Use the partial view returned by the AJAX call to render the modal body, and use a normal Razor form in that partial so edited values can be posted back.

    From the screenshots, OnGetDataResponse(int? id) already returns Partial("_CarPartial", car);. Put the modal markup and the form fields in _CarPartial.cshtml, strongly typed to Car, and use asp-for there. Example:

    @model Car
    
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">Edit car</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label asp-for="CarType" class="col-form-label"></label>
                            <input asp-for="CarType" class="form-control" />
                        </div>
                        <div class="mb-3">
                            <label asp-for="Year" class="col-form-label"></label>
                            <input asp-for="Year" class="form-control" />
                        </div>
                        <div class="mb-3">
                            <label asp-for="Model" class="col-form-label"></label>
                            <input asp-for="Model" class="form-control" />
                        </div>
                        <input asp-for="Id" type="hidden" />
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    

    In the main page (Ajax.cshtml), keep only a container for the partial and load it with AJAX:

    <div id="grid"></div>
    
    <button type="button" class="btn btn-primary" id="load">Load</button>
    
    @section Scripts {
    <script>
        document.getElementById("load").addEventListener("click", async () => {
            const url = '@Url.Page("Ajax", "DataResponse")' + '?id=1';
            const response = await fetch(url);
            if (response.ok) {
                const html = await response.text();
                document.getElementById("grid").innerHTML = html;
                const modalEl = document.getElementById('exampleModal');
                const modal = new bootstrap.Modal(modalEl);
                modal.show();
            }
        });
    </script>
    }
    

    Because _CarPartial is strongly typed to Car, asp-for binds correctly and the inputs are pre-filled with the values from car returned by OnGetDataResponse. When the user edits and clicks Save, the form posts back to the same Razor Page (AjaxModel). Handle the POST in OnPost using the [BindProperty] public Car? Car { get; set; } property:

    [BindProperty]
    public Car? Car { get; set; }
    
    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
    
        // Car now contains the edited values from the modal
        // TODO: save to database or perform other logic
    
        return RedirectToPage();
    }
    

    Key points:

    • Render the modal body and inputs inside the partial view returned by AJAX, not in the main page.
    • Use @model Car in the partial and asp-for on inputs to pre-fill values.
    • Include a hidden Id field so the server knows which entity is being edited.
    • After inserting the partial HTML into the page, programmatically show the Bootstrap modal.
    • Use a normal POST handler (OnPost) to receive the edited values.

    References:


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.