Load HTML into DOM with Ajax and .Net MVC


**This post has been updated and source code linked on GitHub has been modified** See Here:

http://blankstechblog.com/dotnet-mvc-single-page-application-take-two/


This is going to be a quick example of loading HTML requested from the server into a client side template with AJAX.

I was having a discussion at work with a co-worker who has trying to learn some more about newer .Net web frameworks and we got on the topic of loading pages via Ajax like SPA (Single Page Application) applications do and that prompted me to create a quick example.

So starting with your boiler-plate .Net 4.6 MVC app I made a few quick changes.

First in the Layout page (Views/Shared/_Layout.cshtml) I added a simple hyperlink tag with an id and a # href target.

<div class="navbar-collapse collapse">
  <ul class="nav navbar-nav">
    <li>@Html.ActionLink("Home", "Index", "Home")</li>
    <li>@Html.ActionLink("About", "About", "Home")</li>
    <li><a href="#" id="spaLink">SpaTest</a></li>
    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
  </ul>
  @Html.Partial("_LoginPartial")
</div>

Then I added the id “SpaBody” to the div tag surrounding the content of the page

<div id="spaBody" class="container body-content">@RenderBody()

<hr />

&nbsp;

<footer>© @DateTime.Now.Year - My ASP.NET Application </footer></div>

Finally the last edit for the Layout page was a small bit of Javascript and Razor code to call the Action method “SpaTest” from the controller “Home”

<script>
 $("#spaLink").click(function() {
 $("#spaBody").load("@Url.Action("SpaTest","Home")");
 });
</script>

Next I added the Action Result method to the Home Controller (Controllers/HomeController.cs)

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

And last but not least I added a view page for the “SpaTest” page (Views/Home/SpaTest.cshtml) without a layout and with just the html I wanted to insert into the DOM.

@{
 Layout = null;
}

<div>
  <div class="jumbotron">
    <h1>Spa Test!</h1>
    <p class="lead">I am content that was loaded via Ajax!</p>
 </div>
</div>

Now when you click the link for SpaTest in the nav bar it fires the Jquery script which requests the page from the home controller. The server then fetches the page (rendering any Razor code) and returns it as a regular html page. The Jquery method receives the html page from the server and inserts it into the DOM, in the tag specified by the id, removing any previous html that was inside that tag.

Thanks for reading!

Source code is here if you want to play with it:
https://github.com/andyrblank/MVCSpa

One thought on “Load HTML into DOM with Ajax and .Net MVC

Have a question or comment? Why not leave a Reply?