Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference in "return View()" and "return PatialView()" still in MVC 3

So somebody asked me the question:

When would I return View() and when would I return PartialView()?

My immdiate reaction was, if it's a patial use PartialView(). Then I realised that I have quite often returned View() for a partial view with no, apparent, detremental effects?! So what's the point in the return PartialView() call?

I found this question What's the difference between “return View()” and “return PartialView()”. This appears to be particular to MVC2. i.e. talks about .aspx and .ascx control extensions. Using Razor all our views are .cshtml whether they are partial or not.

Which got my thinking is the PartialView() just a hangover from MVC2 and not really relevant in MVC3+ (When using Razor anyway)? Or am I missing some crucial feature of PartialView()?

like image 242
Liam Avatar asked Dec 15 '22 05:12

Liam


2 Answers

tl;dr: PartialView() does not use a layout for the view being returned.


You can set a default layout file within _ViewStart.cshtml (located in the Views folder) which will then be used by all views. By doing that, you avoid having to set the Layout property within each view. PartialView() will not include that layout file or any other.

If you want to return a partial view, e.g. in a child action called using @Html.Action(action, controller), use PartialView. If you want to return a "full" view including the layout, use View().

like image 93
Marius Schulz Avatar answered Dec 28 '22 07:12

Marius Schulz


MSDN Reference:

If you contrast the MSDN definition for ViewResult() Object with the MSDN definition for PartialViewResult() Object

you find the only difference is that ViewResult has an extra property:

public string MasterName { get; set; }

Otherwise, both Objects inherit from ViewResultBase and seem to inherit all other properties and methods from the base class.

Unfortunately, the implementation of the abstract method ExecuteResult() is not published, but I have no doubt it uses the MasterName field to find and render the Master Layer.


Our shared experience:

Just like you, I have returned partial views =using View(). I don't recommend it. But the apparent difference isn't big.

It does seem a touch wasteful to have an extra object just for MasterName, but the more important difference is probably the implementation of ExecuteResult().

When you choose View() method and create a ViewResult Object rather than using PartialView() to create a PartialViewResult Object, you are being less efficient; your application is doing the extra work of checking if your MasterName field is assigned.

like image 39
Dave Alperovich Avatar answered Dec 28 '22 07:12

Dave Alperovich