Header Ads

ASP.NET MVC: How to Use Ajax with JSON Parameters

JSON input format is one of the widely used input format for complex data sharing. In Ajax call, it is necessary to send complex data as input according to business requirements. Since, complex or large input parameters are difficult to manage and share in Ajax call, therefore it is recommended to utilize the power of JSON input format.

Today, I shall be demonstrating the integration of Ajax call by passing JSON format input query parameters using ASP.NET MVC5 platform.


Prerequisites:

Following are some prerequisites before you proceed any further in this tutorial:
  1. Knowledge of Jquery.
  2. Knowledge of HTML.
  3. Knowledge of JavaScript.
  4. Knowledge of Bootstrap.
  5. Knowledge of ASP.NET MVC5.
  6. Knowledge of C# Programming.
The example code is being developed in Microsoft Visual Studio 2019 Professional.

Download Now!

Let's begin now.

1) Create a new MVC web project and name it "MVCAjaxWithJsonParam". 

2) Create target "JSON object Mapper" object class file according to the business requirements. 

3) Create a "Controllers\HomeController.cs" file with default Index method and GetData(...) method with string type input query parameters for Ajax call with following lines of code i.e.

...
        public ActionResult GetData(string jsonInput = "")
        {
            // Initialization.
            JsonResult result = new JsonResult();
            DataTable data = DataTable();
...
            // Deserialize Input JSON String into target Object Mapper.
            RequestObj reqObj = JsonConvert.DeserializeObject<RequestObj>(jsonInput);
...
            // Load Data.
...
            // Filter data with JSON input query parameters.
...                
            // Prepare Ajax Response as JSON Data Result.
            result = this.Json(JsonConvert.SerializeObject(data), JsonRequestBehavior.AllowGet);
...
            // Return info.
            return result;
        }
...

In the above code, I have created a simple “GetData(…)” method which will return data result response in JSON format using  ActionResult data type for the client-side Ajax call. This Ajax method will take single string parameter as JSON string input request query parameter. The most important step in the above code is to deserialize the JSON input request query string into target JSON object mapper according to the business requirements. Then I have loaded my require data in DataTable structure and then, I have applied the JSON string input query filter with OR condition and finally, I have prepared my JSON response.

4) Now, create the subsequent view "Views\Home\Index.cshtml"of "Controllerss\HomeController.cs" index method and add table HTML tag as shown below i.e.

...
    <table class="table table-responsive table-striped table-bordered table-hover"
           id="TableId"
           cellspacing="0"
           align="center"
           width="100%">
    </table>
...

In the above code, I have created a simple responsive Bootstrap style HTML table tag structure. I will populate the data in this table using Ajax call.

5) Now, create the JavaScript file "Scripts\script-custom-ajax.js" with the following lines of code i.e.

...

$(document).ready(function ()
{
    // Initialization
    var jsonInput = { CustomerID: 23, Firstname: "John" };

    $.ajax(
        {
            type: 'POST',
            dataType: 'JSON',
            url: '/Home/GetData',
            data: { jsonInput: JSON.stringify(jsonInput) },
            success:
                function (response)
                {
                    // Generate HTML table.
                    convertJsonToHtmlTable(JSON.parse(response), $("#TableId"));
                },
            error:
                function (response)
                {
                    alert("Error: " + response);
                }
        });
... 

});

...

In the above code, It is important to prepare your JSON object and then convert that JSON object into JSON string. So, I have made an Ajax call to my server-side at the load of the page to get JSON input request query based filter data. To do so, I have converted my input request query JSON object into JSON string and then I have made the suitable Ajax call as shown in the above code. After receiving the processed JSON data from the server-side, I have loaded the JSON data into HTML table, you can utilize any logic of your own to convert JSON data into HTML table.

6) Now, execute the provided solution and you will be able to see the following in action i.e.


Conclusion

In this article, you will learn about the integration of Ajax call by passing JSON format input query parameters using ASP.NET MVC5 platform. You will also learn to create server-side method, which will be called by client-side Ajax call using Jquery. You will learn to make simple client-side Ajax call at the load of the page. You will learn to convert client-side JSON object into JSON string. You will learn to pass JSON input request query to the Ajax call and finally, you will learn to deserialize the Input request query JSON string into target JSON object mapper according to the business requirements.

3 comments:

  1. Hey,
    Very nice, this is very good. i will share it to social media platform. Its very good idea

    There is my website which gives information about technology and gadges
    TechWeb

    keep support

    ReplyDelete
  2. This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting this again. 360DigiTMG PMP Certification
    PMP Certification in Malaysia
    PMP Course in Malaysia
    PMP Course
    PMP training

    ReplyDelete
  3. I have been searching to find a comfort or effective procedure to complete this process and I think this is the most suitable way to do it effectively.
    data science course in malaysia

    ReplyDelete