jQuery Ajax With JSONResult Example in ASP .NET MVC

In this blog post, we will go through a step-by-step example of how to use jQuery AJAX and JSON with .NET MVC to create a simple web application. jQuery AJAX and JSON are powerful tools that can be used to create dynamic and responsive web applications.

Step 1: Create a new .NET MVC project First, we need to create a new .NET MVC project. Open Visual Studio and create a new project, select ASP.NET Web Application (.NET Framework) and give it a name.

Step 2: Create a Controller We will create a controller named "HomeController" by right-clicking on the "Controllers" folder in the Solution Explorer and selecting "Add" -> "Controller". In the "Add Controller" dialog, select "MVC 5 Controller - Empty" and give it the name "HomeController".

Step 3: Add an Action Method We will add an action method named "GetStudent" to our HomeController. This action method will return a JSON object with student details.
public JsonResult GetStudent()
{
    var student = new
    {
        Name = "John Doe",
        Age = 20,
        Grade = "A",
        City = "New York"
    };
    return Json(student, JsonRequestBehavior.AllowGet);
}
Step 4: Create a View We will create a view named "Index.cshtml" by right-clicking on the "Views" folder in the Solution Explorer and selecting "Add" -> "View". In the "Add View" dialog, select "Empty (without model)" and give it the name "Index".

Step 5: Add jQuery We need to add the jQuery library to our project. We can either download the library from the jQuery website or use a CDN. In this example, we will use the CDN.

Add the following code to the head section of the Index.cshtml file:

    


Step 6: Add a Button We will add a button to the view that will trigger the AJAX request. Add the following code to the body section of the Index.cshtml file:

    
    

Step 7: Add the AJAX Request We will use jQuery AJAX to send a request to the GetStudent action method in the HomeController. Add the following code to the body section of the Index.cshtml file:

This code attaches a click event listener to the button with the ID "getStudent". When the button is clicked, it sends a GET request to the GetStudent action method in the HomeController. If the request is successful, it displays the student details in the div with the ID "studentDetails". If there is an error, it displays an error message.
 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
5 + 6 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice