Thursday, November 4, 2010

C# - MVC.net Partial View thru Ajax

There are different ways to load Partial View thru Ajax. What I am presenting here are just those that I've known and tested.

To make a partial view available thru ajax calls, it must inherit the "ViewUserControl":

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CAD.Models.SetupModel>" %>

On your controller, you can check if request is an ajax call and render the partial view:


public virtual ActionResult DetailsTable(SetupModel setup)
        {
            if (Request.IsAjaxRequest())
            {
                return PartialView("DetailsTable", setup);
            }
            else
            {
                return View(setup);
            }
        }

Suppose you have this div to display the ajax response:

<div id="otherForms">
</div>

Here are some samples how to render the partial view thru ajax:

A.

<%= Ajax.ActionLink("Show All", MVC.Setup.DetailsTable(), new AjaxOptions { UpdateTargetId = "otherForms" }) %>


B.

<%= Ajax.ActionLink("Show All", MVC.Setup.DetailsTable(), new AjaxOptions { UpdateTargetId = "otherForms", OnSuccess="refreshOtherForms" }) %>
function refreshOtherForms(response) {
            var html = response.get_data();
            var container = response.get_updateTarget();
            $(container).html(html);
            return false;
}

C.

<a href="#" onclick="refreshOtherForms();return false;">

function refreshOtherForms(response) {
            $('#otherForms').load('<%= Url.Action("DetailsTable", "Setup") %>');
}

D.

<a href="#" onclick="refreshOtherForms();return false;">
function refreshOtherForms(response) {
            $.ajax({
                url: '/Setup/DetailsTable',
                data: { variable1: value1 },
                dataType: 'html',
                success: function (data) {
                    $('#otherForms').html(data);
                }
            });
}

No comments:

Post a Comment