Friday, December 14, 2018

LayoutView in MVC

An application may contain common parts in the UI which remains the same throughout the application such as the logo, header, left navigation bar, right bar or footer section. ASP.NET MVC introduced a Layout view which contains these common UI parts, so that we don't have to write the same code in every page. The layout view is same as the master page of the ASP.NET webform application.

Layout views are shared with multiple views, so it must be stored in the Shared folder. 

Use Layout View

1. You can also override default layout page set by _ViewStart.cshtml by setting Layout property in each individual .cshtml view. For example, the following Index view use _myLayoutPage.cshtml even if _ViewStart.cshtml set _Layout.cshtml.

@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_myLayoutPage.cshtml";
}

2. Specify Layout Page in ActionResult Method

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View("Index", "_myLayoutPage");
    }
}

Rendering Methods
ASP.NET MVC layout view renders child views using the following methods.

RenderBody() Renders the portion of the child view that is not within a named section. Layout view must include RenderBody() method.
RenderSection(string name) Renders a content of named section and specifies whether the section is required. RenderSection() is optional in Layout view.


RenderSection methods specify name of a section such as LeftSection, MiddleSection and RightSection

Points to Remember :

  1. The Layout view contains common parts of a UI. It is same like masterpage of ASP.NET webforms.
  2. _ViewStart.cshtml file can be used to specify path of layout page, which in turn will be applicable to all the views of the folder and its subfolder.
  3. You can set the Layout property in the individual view also, to override default layout page setting of _ViewStart.cshtml
  4. Layout view uses two rendering methods: RenderBody() and RenderSection().
  5. RenderBody can be used only once in the layout view, whereas the RenderSection method can be called multiple time with different name.
  6. RenderBody method renders all the content of view which is not wrapped in named section.
  7. RenderSection method renders the content of a view which is wrapped in named section.
  8. RenderSection can be configured as required or optional. If required, then all the child views must included that named section.



http://www.tutorialsteacher.com/mvc/layout-view-in-asp.net-mvc

No comments:

Followers

Link