0

I'm starting to learn ASP.NET WebAPI and I cannot seem to understand the marriage between the two. I created an Index.cshtml view with the following markup:

<div>
<div>
    <ul data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Search..." id="items">
    </ul>
</div>         
</div>

@section scripts {
<script>
    var apiUrl = '/api/items';

    $(document).ready(function () {
        // Send an AJAX request
        $.getJSON(apiUrl)
            .done(function (data) {
                // On success, 'data' contains a list of items.
                $.each(data, function (key, item) {
                    // Add a list item.
                    $("ul").append("<li><a href='acura.html'>" + item.ItemCode + "</a></li>").listview("refresh");
                });
            });
    });
</script>
}

This view basically gets sent to the browser, but when the browser receives this view, it makes an ajax call to fetch the data using Web API that I defined. But is it me or am I seeing an unnecessary second call here to get the data. Why don't we stick to the original MVC way of thinking (without WebAPI) where the view sends the markup and the data is already embedded in the markup?

I'm seeing two calls here, one for the view and another for the data, is this really more efficient or am I missing something here?

0

3 Answers 3

1

The view must load before any AJAX requests can be made. If you want to load the data with the view without making an additional call to your server, you shouldn't use an AJAX call. AJAX calls are typically for updating page content on the fly or sending data to the server without needing to do a full post back to the server. You can embed the data from the view using a strongly typed view with the model of your choosing or you can populate the view from the ViewBag.

Sign up to request clarification or add additional context in comments.

Comments

1

For every data that is immediately needed, do not make a secondary ajax call. Embed the resource in the page in a javascript object while rendering the page on the server-side. Any ajax needs to be as a result of user interaction.

Embedding not always easy or possible especially if the data comes from another server or application.

Comments

1

Ajax can also enhance the user experience. If I have a page that take 10 seconds to load (for whatever reason), do I let the user stair at a blank screen for 10 seconds? Or do I write a page that brings up a user interfaces stating it's loading data and let the Ajax make the call and wait 10 seconds?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.