I understand that partial views are used to render parts of a view. But I can't understand what's the difference between return View()
and return PartialView()
and when do you use each one.
Views are the general result of a page that results in a display. It's the highest level container except the masterpage. While a partial view is for a small piece of content that may be reused on different pages, or multiple times in a page.
This process determines which view file is used based on the view name. The default behavior of the View method ( return View(); ) is to return a view with the same name as the action method from which it's called.
The primary difference between the two methods is that Partial generates the HTML from the View and returns it to the View to be incorporated into the page. RenderPartial, on the other hand, doesn't return anything and, instead, adds its HTML directly to the Response object's output.
To create a partial view, right-click on view -> shared folder and select Add -> View option. In this way we can add a partial view. It is not mandatory to create a partial view in a shared folder but a partial view is mostly used as a reusable component, it is a good practice to put it in the "shared" folder.
Return View()
- Renders an .aspx|.cshtml page
Return PartialView()
- Renders .ascx|.cshtml Control
View() returns ViewResult
PartialView() returns PartialViewResult
both inherit from ViewResultBase
The difference is described by Reflector below...
public class PartialViewResult : ViewResultBase { // Methods protected override ViewEngineResult FindView(ControllerContext context) { ViewEngineResult result = base.ViewEngineCollection.FindPartialView(context, base.ViewName); if (result.View != null) { return result; } StringBuilder builder = new StringBuilder(); foreach (string str in result.SearchedLocations) { builder.AppendLine(); builder.Append(str); } throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, MvcResources.Common_PartialViewNotFound, new object[] { base.ViewName, builder })); } } public class ViewResult : ViewResultBase { // Fields private string _masterName; // Methods protected override ViewEngineResult FindView(ControllerContext context) { ViewEngineResult result = base.ViewEngineCollection.FindView(context, base.ViewName, this.MasterName); if (result.View != null) { return result; } StringBuilder builder = new StringBuilder(); foreach (string str in result.SearchedLocations) { builder.AppendLine(); builder.Append(str); } throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, MvcResources.Common_ViewNotFound, new object[] { base.ViewName, builder })); } // Properties public string MasterName { get { return (this._masterName ?? string.Empty); } set { this._masterName = value; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With