Pages

Thursday, June 7, 2012

How to load partial view dynamically in ASP.NET MVC using JQuery

Below is the simple implementation which works with custom view engine and view context.
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult LoadTopDestinations()
{
    return PartialView("TopDestinations");
}
And this is how i call the controller from the javascript using jquery post.
function TopDestinationClick() {
    proxy.invoke("/Home/LoadTopDestinations", "", TopDestinationCallback, OnError);

}
And the Javascript is
function serviceProxy(serviceUrl)
{
    var _I = this;
    this.serviceUrl = serviceUrl;
    
    // *** Call a wrapped object
    this.invoke = function(method, data, callback, error) {
        // *** The service endpoint URL        
        var url = _I.serviceUrl + method;
        //alert(url);
        $.ajax({
            url: url,
            data: '',
            type: "GET",
            contentType: "html",
            timeout: 10000,
            success: callback,
            error: OnError
        });
    }
}

// *** Create a static instance
var serviceUrl = "";
var proxy = new serviceProxy(serviceUrl);
And the callback event, just use jquery.html() method to load the partial view result.

No comments:

Post a Comment