Recently I was in need of a way to load content via AJAX on many many pages. Not wanting to repeat myself too much I ended up making an ASP.NET MVC Razor helper method to handle the lifting for me.

The actual JavaScript is simple enough, a basic jQuery AJAX GET request. I included this in my general site JavaScript file.

$(document).ready(function () {
    $(".ajax-load").each(function () {
        var ajaxDom = $(this);
        $.ajax({
            type: "get",
            url: ajaxDom.attr("data-url"),
            dataType: "html"
        }).done(function (result) {
            ajaxDom.html(result);
        }).fail(function(jqXHR, textStatus, errorThrown){
            ajaxDom.slideUp();
            console.log(errorThrown);
        });
    });
});

The HtmlHelper extension that I made returns a 100% width indeterminate progress bar for Bootstrap 3.

public static class HtmlHelperExtensions
{
    public static MvcHtmlString LoadUrlViaAjax(this HtmlHelper helper, string url, string message = "")
    {
        return new MvcHtmlString(
            String.Format(
                @"<div class='ajax-load progress' data-url='{0}'>
                    <div class='progress-bar progress-bar-info progress-bar-striped active' style='width:100%;'>
                        {1}
                    </div>
                 </div>",
            url, message));
    }
}

In the view you'll need to add a reference to the namespace that the HtmlHelperExtensions is contained in.

@using MyProject.ExtensionMethods

Using it! - In your view:

@Html.LoadUrlViaAjax("/some-partial-content", "Loading Your Options!")

About Author

Siva Katir

Siva Katir

Senior Software Engineer working at PlayFab in Seattle Washington.