views:

2790

answers:

2

What is the difference between the controller result named ViewResult and PartialViewResult? More importantly, when is the PartialViewResult used?

+14  A: 

PartialViewResult is used to render a partialview (fx. just a user control). This is pretty nifty for AJAX stuff, i.e.

<script type="text/javascript">
    $.get(
        "/MyController/MyAction",
        null,
        function (data) { $("#target").html(data) }
     );
</script>

and action

public ActionResult MyAction() 
{
    return PartialView("SomeView");
}

where SomeView is a MVC User Control, e.g.:

<div>
   <%= DateTime.Now.ToString() %>
</div>
veggerby
But why is it needed? You can just as easily return a usercontrol with a regular View("SomeView")?
Trevor de Koekkoek
I'd say: mostly semantics. if you check Codeplex source you'll they both inherit from ViewResultBase and the main difference is ViewResult supports specifying master page, PartialViewResult doesn't
veggerby
The important point is the one about the master page. When using PartialViewResult you usually want to return just a chunk of markup, not a whole page with DOCTYPE, <html> tag, script references and so on. It's very useful in Ajax scenarios.
Pawel Krakowiak
it's handy when you have a user control that you don't want to be coupled to any given page. In my current problem, I have a user control in a master. I don't want every page to get it's data source so I need the control to go and get it's data. I suspect that what this action is for..
Josh Robinson
+9  A: 

http://msmvps.com/blogs/luisabreu/archive/2008/09/16/the-mvc-platform-action-result-views.aspx

In practice, you’ll use the PartialViewResult for outputing a small part of a view. That’s why you don’t have the master page options when dealing with them. On the other hand, you’ll use the ViewResult for getting a “complete” view. As you might expect, the Controller class exposes several methods that will let you reduce the ammount of typing needed for instanting these types of action results.

Generally speaking, ViewResult is for rendering a page with optional master, and PartialViewResult is used for user controls (likely responding to an AJAX request).

eyston