Wednesday, January 8, 2014

Is there really no difference between a partial view and a regular view in MVC?

The question


I've read several posts on the net about there being no real difference between a partial view and a regular view in ASP.NET MVC, only that the convention of using them was different. Is this really the case?



I decided to find out the details for myself as part of the new "MVC for Web Forms Developers" course I'm working on for pluralsight.com so I could see exactly what all this entailed outside of just being a convention difference. Let it be known, there is indeed several differences you should be aware of. This post isn't meant to state when you should use one vs the other, there are plenty of resources for that. Here we just want to delve into how they are different, which in turn can help you decide when to use a View vs PartialView (and to confuse things more the decision there is really View vs PartialView vs Html.Action vs Html.Partial vs Ajax in any combination)


The differences


The differences that were obvious from the code are
  1. Partial Views don't have a layout processed. Very important to know.
  2. Partial Views don't check for a _ViewStart.cshtml. Note this is typically where layouts are specified but technically you could specify one in your partial and it would be ignored. Very important to know.
  3. Partial Views can throw a slightly different exception, the details included to InvalidOperationException in PartialViewResult vs ViewResult classes. This is pretty minor.

There is a slight difference in how they are processed.
Lets look at the code, shall we?

First, the differences between a PartialViewResult and a ViewResult as contained in the following files from the MVC source code:
  1. c:\source\aspnetwebstack\src\System.Web.Mvc\PartialViewResult.cs (link to source here)
  2. c:\source\aspnetwebstack\src\System.Web.Mvc\ViewResult.cs (link to source here)


Lets dive into FindPartialView and FindView. These are the functions called when you "return View()" and "return Partial()" from inside a controller.

The comparison of PartialViewResult and ViewResult


First check out a comparison side by side, this may give you an easy quick view with one of the best tools of all time,Beyond Compare


The codez


 public virtual ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (String.IsNullOrEmpty(partialViewName))
            {
                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "partialViewName");
            }

            string[] searched;
            string controllerName = controllerContext.RouteData.GetRequiredString("controller");
            string partialPath = GetPath(controllerContext, PartialViewLocationFormats, AreaPartialViewLocationFormats, "PartialViewLocationFormats", partialViewName, controllerName, CacheKeyPrefixPartial, useCache, out searched);

            if (String.IsNullOrEmpty(partialPath))
            {
                return new ViewEngineResult(searched);
            }

            //********* note the call here to CreatePartialView *****
            return new ViewEngineResult(CreatePartialView(controllerContext, partialPath), this);
        }

        public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (String.IsNullOrEmpty(viewName))
            {
                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "viewName");
            }

            string[] viewLocationsSearched;
            string[] masterLocationsSearched;

            string controllerName = controllerContext.RouteData.GetRequiredString("controller");
            string viewPath = GetPath(controllerContext, ViewLocationFormats, AreaViewLocationFormats, "ViewLocationFormats", viewName, controllerName, CacheKeyPrefixView, useCache, out viewLocationsSearched);
            string masterPath = GetPath(controllerContext, MasterLocationFormats, AreaMasterLocationFormats, "MasterLocationFormats", masterName, controllerName, CacheKeyPrefixMaster, useCache, out masterLocationsSearched);

            if (String.IsNullOrEmpty(viewPath) || (String.IsNullOrEmpty(masterPath) && !String.IsNullOrEmpty(masterName)))
            {
                return new ViewEngineResult(viewLocationsSearched.Union(masterLocationsSearched));
            }
            //********* note the call here to CreateView *****
            return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);
        }

The differences in view processing


The function calls below to create a partial view or a regular view do indeed differ. One has a pipeline that uses a layout, the other doesn't. The regular view processing uses viewstart pages as well. For those unfamilar with the viewstart file, this is a file MVC looks for since MVC3.

MVC will look in the /Views/Shared folder and in the current view folder as well for a file named _ViewStart.cshtml. This file contains code that will be executed before the view is processed, typically it's used to store the path to the layout in it and again, can be set for all views or overridden in a particular views folder, ex /Views/Customer/_ViewStart.cshtml to set a different Layout for views in that folder as one example.
@{
    Layout = "~/Views/Shared/_MasterPage.cshtml";
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            //**NOTE a partial view has a null layout and runViewStartPages is false! **
            return new RazorView(controllerContext, partialPath,
                                 layoutPath: null, runViewStartPages: false, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator)
            {
                DisplayModeProvider = DisplayModeProvider
            };
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            //note the usage of a masterPath below.
            var view = new RazorView(controllerContext, viewPath,
                                     layoutPath: masterPath, runViewStartPages: true, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator)
            {
                DisplayModeProvider = DisplayModeProvider
            };
            return view;
        }



In closing


So there are some differences as probably expected. Nothing groundbreaking but it is important to understand the shortcut pipeline the PartialView takes hence making them perform a bit better as well. Ok, now you know the exact differences and have seen it from the source, in other words - heard it from
Enjoy!

60 comments:

  1. More informative subject.model view controller(MVC) is a framework for building web application and main part of asp.net. The Keshri Software Solutions provides Web Application development,Website Promotions, Search Engine Optimizations services . We have a very dedicated and hard working team of web application developers(asp.net/c#/sql server/MVC) , Search engine optimizers. Fast communication and quality delivery product is our commitment.

    To get more details please log on to - http://www.ksoftware.co.in .

    ReplyDelete

  2. This is nice information,, Thanks for sharing this information,, Its very useful to me
    software development

    ReplyDelete
  3. The article was awesomely described here by the author. I really enjoyed reading interesting post from this blog.
    Software Development Company in Indore

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. For Razor users, both regular and partial views are cshtml files. There is no actual difference between them.

    Web development company in Indore

    ReplyDelete
  6. I am very glad to read your blog post it’s very useful for everyone. I am completely satisfied with your blog.

    E-commerce web Design Company in India

    ReplyDelete
  7. We welcome to Exoticdelhiescorts provide you with a hot Hyderabad model or girl that you can make love in Hyderabad.
    http://www.exoticdelhiescorts.in/call-girls-hyderabad.html

    ReplyDelete
  8. This is detailed and excellent information. Your blog is like professional! Do you want to find best premium wordpress templates for any kind of business? go here https://wordpresstemplates.ch/

    ReplyDelete
  9. Really great blog, it's very helpful and has great knowledgeable information. Thanks for sharing, keep updating such a good informative blog.

    Digital Transformation Services | Austere Technologies

    ReplyDelete
  10. VERY INFORMATIVE BLOG. KEEP SHARING SUCH A GOOD ARTICLES.

    cloud Services | Austere Technologies

    ReplyDelete
  11. Really great blog, it's very helpful and has great knowledgeable information. Thanks for sharing, keep updating such a good informative blog.

    Best Software Company | Austere Technologies

    ReplyDelete
  12. Very good informative article. Thanks for sharing such nice article, keep on up dating such good articles.

    IOT SERVICES | INTERNET OF THINGS | Austere Technologies

    ReplyDelete
  13. Looking great article, contains very useful information. Thanks much for sharing and please do keep on sharing...
    Best Online Software Training Institute | Asp.Net MVC Training

    ReplyDelete
  14. I am thankful to this blog for assisting me. I added some specified clues which are really important for me to use them in my writing skill. Really helpful stuff made by this blog.
    ทํา สติ๊กเกอร์ สินค้า

    ReplyDelete
  15. Hi Thanks for the nice information its very useful to read your blog. We provide best System Integration Services

    ReplyDelete
  16. Hi Thanks for the nice information its very useful to read your blog. We provide best Chartered Accountancy

    ReplyDelete
  17. Hi Thanks for the nice information its very useful to read your blog. We provide best Certified Financial Analyst

    ReplyDelete
  18. Thank you for sharing this valuable information. But get out this busy life and find some peace with a beautiful trip. book ANDAMAN TOUR PACKAGE @24599

    ReplyDelete
  19. Thank you for sharing this valuable information. But get out this busy life and find some peace with a beautiful trip. book BEST ANDAMAN HONEYMOON PACKAGE @5999

    ReplyDelete
  20. Hi Thanks for the nice information its very useful to read your blog. We provide Software Development Services

    ReplyDelete
  21. Hi Thanks for the nice information its very useful to read your blog. We provide best Chartered Institute Of Management Accountants

    ReplyDelete
  22. Women and young women see the world specific way. They both have substitute point of view in understanding the world in an unexpected way. Furthermore, they interface with everybody shockingly. Young women are twelve, yet women are a need.
    goa escort

    ReplyDelete
  23. Thanks for sharing this with so much of detailed information, its much more to learn from your article. Keep sharing such good stuff.
    VIVO Mobile Service Center in Coimbatore
    Sony Mobile Service Center in Coimbatore



    ReplyDelete
  24. Girls in South Delhi are well-renowned across India for their open mind and also stylish personality. Friendly, well-read and also fashionable, the South Delhi ladies are the ideal business for your leisure time, at your certain event Delhi Escort

    ReplyDelete
  25. Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts.

    TekSlate Online Training's

    ReplyDelete
  26. Are you looking for escort advantage in Delhi, we give the best that would absolutely change your experience. Our escorts are arranged precisely to pass on best organization that you are scanning for.

    Delhi Escorts

    ReplyDelete
  27. Thanks for sharing the useful content please do keep on sharing…

    Software Training courses in hyderabad | HTML course

    ReplyDelete
  28. The eye-getting self-regulating escorts in Goa perceive how to make indisputably the most goal and to an extraordinary Goa Escorts degree key minutes for the clients. On the off chance that a man needing to get an entire night with Goa escort, atthat point he would be a head among the most respected men. The contact females inGoaare intriguing, eye-getting and unimaginable from each perspective

    ReplyDelete
  29. Thank you for your post. This is excellent information.

    CEH Training In Hyderbad

    ReplyDelete
  30. I really appreciate your efforts. I found this article quite interesting and informative especially the quality of content that I have read here really inspire me. I have found another blog for the same quality content
    Digital Marketing in Bhopal

    ReplyDelete
  31. Everybody has to take the services of a girl like Vida, when the company may be available for every girl of her time, which is also found in the Bangalore City May, which will serve you. Plz you can visit to Mg.Road , Bangalore and the direct call to me : 7022789089
    https://www.payalpandya.com
    bangalore escorts
    escorts in Bangalore
    bangalore escorts service
    bangalore escorts agency
    escort service in bangalore
    bangalore escort girls
    escorts service bangalore

    ReplyDelete
  32. Nice post, very useful blogs with very useful information, thank you for sharing this post web application development company

    ReplyDelete
  33. Everything is very open with a very clear clarification of the issues. It was truly informative. Your website is useful. Many thanks for sharing! Take a look also at web development and web development company

    ReplyDelete
  34. Only one out of every odd female escort for social event in Hyderabad offer their butt for some butt-driven, so guarantee before the get-together comes that everything has been shown all together for both of you to appreciate.
    Hyderabad Escorts
    Independent Call Girl in Hyderabad

    ReplyDelete
  35. Superlative efficient Goa escort organizations offer a wide scope of selective administrations from a high social class. These closeness can made everything from giving you an accomplice for a conference, most prominent undertakings travel visits. Would you like to make the most of your get-away? Take a journey with an attractive lady or simply appreciate a night around the city
    Goa Escorts

    ReplyDelete
  36. hello reshab here please follow our link for all vip escorts in bangalore complete details best escort service in bangalore




    best escort service in bangalore
    escort service in bangalore
    escort in bangalore
    escort bangalore
    bangalore escort

    ReplyDelete
  37. Hey Really Thanks for sharing the best information regarding oracle,hope you will write more great blogs.

    Workday Online Training

    ReplyDelete
  38. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    apache spark online training

    ReplyDelete
  39. Trucking Cube Provide Freight Charges, Lorry hires Bulk Transport, Cheapest Truck Rental Company, Hire a Truck, etc. If you want this kind of services at an affordable cost then contact Trucking Cube.

    International Freight Forwarders
    Truck Hire
    Budget Moving Truck

    ReplyDelete
  40. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    java training in Bangalore

    ReplyDelete

Note: Only a member of this blog may post a comment.