Mark
Mark

Reputation: 404

How to use partial views

I'm coming to a part in my MVC 3 page where I need to do a JQuery $.Ajax callback, but unlike before where I have returned some simple values and handled updating the UI using JQuery I need to refresh the part of the page that displays the main ViewModel data. So in effect it's almost as if I need to do a callback but instead of returning the JSonResult I want to return the original View?? I'm pretty sure though that I need to be thinking about using partial views? Could anyone advise or perhaps point me towards a good tutorial?

Thanks in advance.

Upvotes: 0

Views: 1200

Answers (1)

robmzd
robmzd

Reputation: 1823

If I understand correctly. In this sort of scenario I usually re-use the same action but return either a full or partial view based on the IsAjaxRequest method.

    public ActionResult MyAction(string someParam)
    {
        //...

        if (Request.IsAjaxRequest())
        {
            return PartialView(model);
        }
        else
        {
            return View(model);
        }
    }

This can then be called in jQuery using something like:

$("a.myAction").click(function (event)
{
    event.preventDefault();
    var button = $(this);

    // Get more results using ajax
    $.get(button.attr("href"), function (data)
    {
        // Add the new content 
        $('div#myActionResult').empty().html(data);
    }, "html");
}

You may need to POST instead or change the Url to include a query string if you want to send data to the action to change the view.

Upvotes: 2

Related Questions