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.

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

@RenderBody()
 
© @DateTime.Now.Year - My ASP.NET Application 

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”

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

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;
}

Spa Test!

I am content that was loaded via Ajax!

</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

Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s