ASP.NET MVC > Ajax

List records using JSON in ASP.NET MVC

How to list records from database using JSON in ASP.NET MVC?


To know more about JSON, read jQuery Tips & Tricks ebook.

In short, JSON is a light weight data format used to communicate from-to server with JavaScript, read more here. In order to list records from database using JSON in ASP.NET MVC, we can follow below approach. This is very useful as we only get the actual data from database not the data along with html formatting from the server (as in previous post). Formatting of the data and displaying it to the user will be the responsibility of the JavaScript/jQuery. This is considered faster and better than getting formatted data from the server.

Create following action methods

CONTROLLER CODE

       public ActionResult IndexJson()
        {
            return View();
        }

        public JsonResult SearchPeopleJson(string keyword)
        {
            var data = db.PersonalDetails.Where(f =>
f.FirstName.Contains(keyword)).ToList();

            var jsonData = Json(data, JsonRequestBehavior.AllowGet);
            return jsonData;
        }

The first Action method simply returns the IndexJson view.

In the second Action method, we are filtering the data based on keyword from the database and converting it into JSON format using Json method and returning to the view. Notice that the return type of this action method JsonResult.

VIEW CODE (IndexJson view)

@{
    ViewBag.Title = "IndexJson";
    AjaxOptions options = new AjaxOptions
    {
        Confirm = "Are you sure to start search?",
        LoadingElementId = "divLoading",
        OnSuccess = "processDataMethod",
        Url = Url.Action("SearchPeopleJson")
    };
}
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<script type="text/javascript"> function processDataMethod(data) { var output = $("#searchResult"); output.empty(); for (var i = 0; i < data.length ; i++) { var person = data[i]; output.append("<tr><td>" + person.AutoId + "</td><td>" + person.FirstName + "</td><td>" + person.LastName + "</td><td>" + person.Age + "</td><td>" + person.Active + "</td></tr>"); } } </script> <h2>IndexJson</h2> <table style="width: 100%;"> <thead> <tr> <th>AutoId</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>Active</th> </tr> </thead> <tbody id="searchResult"> </tbody> </table> @using (Ajax.BeginForm(options)) { <div id="divLoading" style="color: red; background-color: yellow; fontsize: larger; display: none;"> Loading .... </div> <div> @Html.TextBox("keyword") <button type="submit" id="btnSearch">Search</button> </div> } @Scripts.Render("~/bundles/jqueryval") <script> $("#btnSearch").trigger("click"); </script>

In the above view, first we have created the instance of AjaxOptions and set its properties

  1. Confirm – used to ask a confirmation message from user before sending Ajax request
  2. LoadingElementId – element to display while the Ajax processing is going on
  3. OnSuccess – function to call when Ajax request is successful
  4. Url – URL where to send the Ajax request

Then as usual, we have referenced the jquery.unobtrusive-ajax.min.js file that is needed in order to work with @Ajax helper methods.

When the Ajax request is successful, we are calling processDataMethod (see above) function. In this function, we are getting the searchResult element into output variable and making it empty so that new data can be populated. Next, we are looping through the Json data being returned from the server and appending to the output variable (that is nothing the searchResult element). Notice that while appending, we are also using html <tr>, <td> element to format data as per the table structure. In the previous example, responsibility of formatting the data being returned from the server was on PartialView.

In the remaining code, a table structure has been formed with the header and <tbody> as searchResult.

Next, we are creating a @Ajax form with AjaxOptions defined above. This form has a div with Loading … message that shows while the Ajax process is going on.

In the last Script block, we are triggering the “click” event of the button so that as soon as the page loads, the form is submitted and default data is displayed on the page.

On click of the Search button after entering any character in the TextBox, the Ajax request is sent to SearchPeopleJson action method defined above that returns the filtered Json data accordingly. The returned data is converted into <tr>, <td> format by processDataMethod function and set into “searchResult” element.

 Views: 32054 | Post Order: 113



Write for us






Hosting Recommendations