ASP.NET MVC > Web API

List records using Web API in ASP.NET MVC

How to list records from database by consuming ASP.NET Web API from ASP.NET MVC View?


To demonstrate listing records from the database by consuming ASP.NET Web API from ASP.NET MVC View, we have created a simple controller action method that following view.

CONTROLLER ACTION METHOD

public ActionResult ListRecords()
{
    ViewBag.Title = "List Records";

    return View();
}

Above action method simply returns following view. No records from database is returned to below view in the first request.

VIEW CODE

@model IEnumerable<MVC_Web_API.Models.PersonalDetails>

@{
    ViewBag.Title = "ListRecords";
}

<h2>ListRecords</h2>

    <p>
        @Html.ActionLink("Create New", "Create")
    </p>

    <label>Keyword</label>
    @Html.TextBox("keyword")
    <button id="btnSearch">Search</button>
    <table class="table">
        <tr>
            <th>Auto ID</th>
            <th>@Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>@Html.DisplayNameFor(model => model.LastName)
            </th>
            <th>@Html.DisplayNameFor(model => model.Age)
            </th>
            <th>@Html.DisplayNameFor(model => model.Active)
            </th>
            <th>Delete </th>
        </tr>
        <tbody id="tableRows"></tbody>
    </table>

    <script type="text/javascript">
        $(function () {
            LoadAll();
        });
        function LoadAll()
        {
            $.ajax(
            {
                //url: '/api/PersonalDetails/GetPersonalDetails',
                url: 'http://localhost:28206/api/PersonalDetails/',
                type: 'GET',
                dataType: 'json',
                success: function (data, status, xhr) {
                    processDataMethod(data);
                },
                error: function (xhr, status, error) {
                    alert(error);
                }
            });
        }

        function processDataMethod(data) {
            var output = $("#tableRows");
            output.empty();
            for (var i = 0; i < data.length ; i++) {
                var person = data[i];
                output.append("<tr><td><a href='javascript:ShowDetails(" + person.AutoId
                + ")'>" + person.AutoId + "</a></td><td>" + person.FirstName + "</td><td>" +
                person.LastName + "</td><td>" + person.Age + "</td><td>" + person.Active +
                "</td><td><a style='color:red;' href='javascript:DeleteRecord(" + person.AutoId +
                ")' title='Delete details'>Delete</a></td></tr>");
            }
        }
    </script>

The HTML part of the view just creates a table with heading coming from the Model. After that <tbody> element is the placeholder where the records returned from the API will be populated.

Listing records

When the page loads, LoadAll() JavaScript function will be called.

In LoadAll() function, we are calling /api/PersonalDetails url that will call the GET method of the PersonalDetails controller. As in this controller only one GET method is there whose name is GetPersonalDetails() so this method will be automatically called.

CONTROLLER ACION METHOD

// GET api/PersonalDetails
public IQueryable<PersonalDetails> GetPersonalDetails()
{
    var data = db.PersonalDetails;
    return data;
}

The above action method returns all records from the PersonalDetails table of the database.

In LoadAll() javascript function, we are setting following

  1. url – api to call that will give us data
  2. type – type fo request to send
  3. dataType – type of data this function expect from the server
  4. success - function to call when the data is processed successfully on the server
  5. error - function to call when the server couldn’t process the data successfully (action method of the Web API controller)

Notice that in the success parameter of the LoadAll() function, we are calling processDataMethod function that find out the <tbody> element, make it empty and then loop through each data item returned from the ASP.NET Web API, format it and append it to the <tbody> element.

We will see the search, delete functionality in following posts.

 Views: 21724 | Post Order: 123



Write for us






Hosting Recommendations