What's the difference between “return View()” and “return PartialView()”

前端 未结 3 1754
孤独总比滥情好
孤独总比滥情好 2020-12-24 11:19

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

3条回答
  •  轮回少年
    2020-12-24 11:32

    Return View() - Renders an .aspx|.cshtml page

    • Renders a normal .aspx page that can also contain Partial Views

    Return PartialView() - Renders .ascx|.cshtml Control

    • Renders a segment of HTML to the browser that can be requested through AJAX or Non-AJAX requests alike.

    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;
          }
       }
    }
    

提交回复
热议问题