LDNDeveloper

Andrew Pallant

Software & Web Developer


Donate To Support My Blog Donate if this post helped you. Coffee money is always welcomed!




Dynamically Load MVC Partials Using jQuery

Physical Link: 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.

The post Dynamically Load MVC Partials Using jQuery appeared first on Software Developer In London.

Author:
Categories: jQuery, Web, DotNet, MVC


Google | humanstxt.org | Andrew Pallant's Blog Site
©2017 LdnDeveloper
rolex replica replica watches rolex replica