Share via

How to read c# data object from server with AJAX and show its fields in html

Pablo The Tiger 186 Reputation points
2026-03-06T13:10:16.67+00:00

Hello,

I'm continuing learning AJAX and web dev. This time I'm trying to read an object from the server by AJAX and fill the inputs (textboxes) in the html ... but it does nothing.

I attach the html and the server side .cs

I will appreciate your help. Thanks!

@page
@model AjaxModel
<h2>Ajax Partial Example</h2>
<p><button class="btn btn-primary" id="load">Load</button></p>
<div id="grid" style="background-color: blue">
    <label asp-for="car.Brand" class="form-label">Brand:</label>
    <input type="text" asp-for="car.Brand" class="form-control" />
    <label asp-for="car.Year" class="form-label">Year:</label>
    <input type="text" asp-for="car.Year" class="form-control" />
    <label asp-for="car.Price" class="form-label">Price:</label>
    <input type="text" asp-for="car.Price" class="form-control" />
</div>
@section scripts {
    <script>
        document.getElementById('load').addEventListener('click', () => {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    alert("AAAAAAAA");
                    @Model.car = JSON.parse(this.responseText);
                }
            };
            xhr.open('get', '?handler=DataResponse?id=1', true);
            xhr.send();
        });
    </script>
}

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebAppRpAjax.Pages
{
    public class AjaxModel : PageModel
    {
        [BindProperty]
        public Car? car {  get; set; }
        public JsonResult OnGetDataResponse(int id)
        {
            Car[] cars =
            {
                new Car { Brand = "Ford", Year = 2022, Price = 20000 },
                new Car { Brand = "Renault", Year = 2019, Price = 25000 },
                new Car { Brand = "Audi", Year = 2025, Price = 40000 }
            };
            car = cars[id];
            JsonResult json = new JsonResult(car);
            return json;
        }
    }
    public class Car
    {
        public string? Brand { get; set; }
        public int Year { get; set; }
        public int Price { get; set; }
    }
}

Pablo

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

Answer accepted by question author
  1. Jack Dang (WICLOUD CORPORATION) 14,955 Reputation points Microsoft External Staff Moderator
    2026-03-09T03:56:02.44+00:00

    Hi @Pablo The Tiger ,

    Thanks for reaching out.

    The issue here is that the line below is mixing server-side Razor/C# with client-side JavaScript, which won’t work:

    @Model.car = JSON.parse(this.responseText);
    

    @Model.car is evaluated on the server when the page is rendered, while JSON.parse(...) runs later in the browser after the AJAX request completes. By that time, the Razor code has already finished executing, so the browser cannot assign values back to the server-side model.

    Instead, the approach is to parse the JSON response in JavaScript and then populate the input fields directly in the page (DOM).

    For example:

    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var car = JSON.parse(this.responseText);
    
            document.querySelector("[name='car.Brand']").value = car.brand;
            document.querySelector("[name='car.Year']").value = car.year;
            document.querySelector("[name='car.Price']").value = car.price;
        }
    };
    

    Your handler (OnGetDataResponse) is already returning the Car object as JSON correctly, so once you parse the response and assign the values to the inputs on the client side, the fields should populate as expected.

    Also, please treat the snippet above as a general reference. Depending on how your page is structured (input names, selectors, or layout), you may need to adjust the selectors or logic slightly 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.

    You found this answer helpful.

Answer accepted by question author
  1. SurferOnWww 5,491 Reputation points
    2026-03-07T01:07:13.27+00:00

    This time I'm trying to read an object from the server by AJAX and fill the inputs (textboxes) in the html ... but it does nothing.

    I suggest that you use partial view to render html source in the div tag. In addition, although they are not the main issues in this question, please consider adding the id to the Car class and replace the XMLHttpRequest with the fetch API.

    Shown below is working sample:

    Ajax.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; }
        }
    }
    

    _CarPartial.cshtml (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

    You found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Marcin Policht 82,355 Reputation points MVP Volunteer Moderator
    2026-03-06T15:52:09.69+00:00

    Looks like you are mixing server-side C# Razor code with client-side JavaScript.

    As far as I can tell, this line inside your script is invalid:

    @Model.car = JSON.parse(this.responseText);
    

    @Model.car is evaluated on the server when the page is rendered, before the browser even receives the page. AJAX runs later in the browser, so JavaScript cannot assign values to Razor model properties this way.

    Instead, you should parse the JSON response in JavaScript and manually fill the input fields.

    Another important consideration is that the asp-for tag helper generates id attributes automatically. For asp-for="car.Brand" the generated id will be car_Brand, and similarly car_Year and car_Price.

    Try modifying your JavaScript like this:

    document.getElementById('load').addEventListener('click', () => {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
    
                var car = JSON.parse(this.responseText);
    
                document.getElementById("car_Brand").value = car.brand;
                document.getElementById("car_Year").value = car.year;
                document.getElementById("car_Price").value = car.price;
            }
        };
        xhr.open('get', '?handler=DataResponse&id=1', true);
        xhr.send();
    });
    

    Also your array has indexes 0,1,2 but you are calling id=1. That is fine, but if you ever call id=3 it will throw an exception. Usually you would do something like:

    car = cars[id];
    return new JsonResult(car);
    

    which you already have, but just be aware of the index range.


    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin


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.