@Blog.Author(Nandip Makwana) .LearningExperience(ASP.NET, ASP.NET MVC, IIS, jQuery & Technology Surrounding it...)

September 29, 2012 comment

PartialViewResult in ASP.NET MVC controller

return PartialView()… yeah as it suggests it will return partial view but I think many developer does not know about PartialViewResult or have never used it. So let’s have quick discussion on it.

Let start with scratch, as we know @Html.Partial is used to inject partial view markup inside another view and while using @Html.Partial, it will not render layout view simply it will render content of partial view without applying layout view. It is very much necessary because the partial view content will be rendered within another view (or sometime partial view) and hence that view has already applied layout view so there is no need to apply layout view again on partial view. One more important aspect is that generally partial view markup will be reflected as a part of page but not directly as a page (read again!) and layout view contain markup for whole page layout and not for specific part of page. So again no need to apply layout view while rendering partial view.

It is pretty much clear that we can use @Html.Partial for rendering partial view within another view but many a times we need to return partial view from action method. return View() returns ViewResult instance from action method and ViewResult apply layout view. One of the common requirements of returning partial view from action method is that many times we are requesting page markup on demand. For e.g. user clicks on accordion header and it send AJAX request and fetch markup and fill accordion content area. Many times we are fetching popup content with AJAX request and at that time we have to call action method! This is where PartialViewResult (and of course ASP.NET MVC flexibility) comes in picture. In such scenario we can return PartialViewResult from action method by return PartialView() and all is done. PartialViewResult will not apply layout view so we can directly use it to fill page area or popup content or wherever layout markup is not required. I have seen many developers creating blank/empty layout view for same purpose. Following is pseudo code for returning partial view from action method.

if (Request.IsAjaxRequest())
    return PartialView();
    return View();

So this is all about partial view in ASP.NET MVC. You can follow me @NandipMakwana for more update on twitter and you can even read ASP.NET MVC 4 article series here.

comments powered by Disqus

Featured Content

Resources & Tools

About Nandip Makwana

Nandip Makwana is passionate about digital world and web. He completed his Masters in Computer Application in June 2011. Currently he is working as a Software Engineer. He has shown great promise and command over ASP.NET and technologies surrounding it during his academic years and professorial life...continue reading