Dynamically Load MVC Partials Using jQuery

Normally I do my examples in C#, but lately I have noticed a lack of VB.NET examples. Therefore, this example is in VB.NET.

I have searched long and hard to find a way to dynamically load MVC partials. I had tried to find a solution a few times, but quickly gave up. I figured there must be a way. Then I remembered how I used to create on the fly images using an HTML image control and simple URL to an ASPX page which served up the image ( another blog topic ). Through this latest realization and a little searching I have pieced together a working model. The piece I was missing was having the controller return a PartialView
.

To dynamically load a MVC partial, you first need to create a main view with a div content properly defined with a unique ID (index.vbhtml).

<h1>Main Content<h1>
<div id="divListOfStuffPartial">

</div>

Then you will need to create your partial that you want to load dynamically (ListOfStuff.vbhtml).

<h1>Make this content Dynamic<h1>
<div>
     <div>
          <li>Item 1</li>
          <li>Item 2</li>
     </div>
</div>

Create a controller with two methods. One to load the main view and one that you will use to load the dynamic partial (HomeController.vb).

Namespace Controllers
    Public Class HomeController
        Inherits Controller

        Function Index() As ActionResult
            Return View()
        End Function

        Function ListOfStuff() As ActionResult
            Return PartialView()
        End Function
    End Class
End Namespace

The loading of the partial is now easy and can be done using a jQuery statement. Put the code either in the main view or a JS file that is referenced in the main view.

    function loadList()
    {
        $("#divListOfStuffPartial").load( "@(Html.Raw(Url.Action("ListOfStuff", "Home")))");
    }();

Tah-Dah! We Are done.

Andrew Pallant (@LdnDeveloper) has been a web, database and desktop developer for over 16 years. Andrew has worked on projects that ranged from factory automation to writing business applications. Most recently he has been heavily involved in various forms for ecommerce projects. Over the years Andrew has worn many hats: Project Manager, IT Manager, Lead Developer, Supervisor of Developers and many more - See more at: http://www.unlatched.com/#sthash.8DiTkpKy.dpuf

Posted in jQuery, Web Tagged with: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*