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 Partia
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;
}
}
}
return PartialView() returns HTML code fragment and it is used with ViewUserControls - ASCX files. The main advantage of using "return PartialView()" is when you don't want to render all the other HTML page stuff, like HTML, BODY, HEAD tags.
One of the most common uses by me is when I want to render just the user control based on whether the request to an action is AJAX call.
So I have a View called MyControl.aspx where I use RenderPartial HTML helper and I have a partial View named MyControl.ascx where I do the actual render.
I can switch between those two in my controller action like this:
if (Request.IsAjaxRequest())
return PartialView("MyControl"); // this renders MyControl.ascx
return View(); // this render MyControl.aspx
A controller action typically returns a PartialView when AJAX is used, and an update of the page region represented by the partial view is performed. The normal way to use partial views is simply to call Html.RenderPartial
inside your main view.