ASP.NET MVC 4 - Layout and Section in Razor

Introduction 

Suppose You are developing an ASP.NET web application and you want to maintain a consistent look and feel across all the pages within you web application then you have two option first one is design head, body and footer section on each page. In this approach you need to write more code on each page so ASP.NET 2.0 introduce the concept of "Master Pages" which helps enable this when using .aspx based pages or templates. It is your second option. Razor also supports this concept with a feature called "layouts" - which allow you to define a common site template, and then inherit its look and feel across all the views/pages on your web application. 

Create an MVC Application 

I am going to create MVC application using Visual Studio 2012. So let's see step by step that how to create MVC application. 

Step 1: Go to "File"—"New" after that click on "Project..". 

Step 2: Choose "ASP.NET MVC 4 Web Application" from list after that give the application name "LayoutMvcApplication" and set path in location input where you want to create application. 

Step 3: Now choose Project Template "Empty" and select "Razor" as view engine from dropdown list. 

Create Layout for Application 

Layout is used to consistent look and feel of all pages of web application so we create a layout for web application. Let's see step by step 

Step 1: Create "Content" folder in root directory of the web application. 

Step 2: Create Style sheet "Site.css" under content folder. That CSS file contains all css classes these are need during consistent web application page design. 

Step 3: Create "Shared" folder under "View" folder. 

Step 4: Create "_Layout.cshtml" file under the "Shared" folder. The file "_Layout.cshtml" represents the layout of each page in the application. Right click on Shared folder in solution explorer after that go to "Add" item and click on View. 

MVC-1.jpg

<! DOCTYPE html >

html lang ="en">

head >

    < meta charset ="utf-8" />

    < title > @ ViewBag.Title - Code Express </ title >

    < link href ="~/favicon.ico" rel ="shortcut icon" type ="image/x-icon" />

    < link rel ="stylesheet" href =" @ Url.Content( "~/Content/Site.css" )" />

</ head >

body >

    < header >

            < div class ="content-wrapper">

                < div class ="float-left">

                    < p class ="site-title">

                        @ Html.ActionLink( "Code Express" , "Index" , "Home" )

                    </ p >

                </ div >

                 < div class ="float-right">                    

                    < nav >

                        < ul id ="menu">

                            < li > @ Html.ActionLink( "Home" , "Index" , "Home" ) </ li >

                            < li > @ Html.ActionLink( "About" , "About" , "Home" ) </ li >                           

                        </ ul >

                    </ nav >

                </ div >

            </ div >

        </ header >

    < div id ="body">

        @ RenderSection( "featured" , required: false )

        < section class ="content-wrapper main-content clear-fix">

                @ RenderBody()

            </ section >

    </ div >

    < footer >

            < div class ="content-wrapper">

                < div class ="float-left">

                    < p > &copy; @ DateTime .Now.Year – Code Express </ p >

                </ div >

            </ div >

        </ footer >

</ body >

</ html In this layout we are using some Html helper method and some other system defined methods so let's see these methods one by one. 

Url.Content() - Content() method is a method of UrlHelper class. It used to Converts a virtual (relative) path to an application absolute path. It has one parameter of string type that is virtual path of content. It returns application the absolute path. If the specified content path (parameter of method) does not start with the tilde (~) character, this method returns contentPath unchanged. Url.Content() makes sure that all links works no matter if the site is in a virtual directory or in the web site root. 

Html.ActionLink() - The easiest way to render an HTML link in is to use the HTML.ActionLink() helper. With MVC, the Html.ActionLink() does not link to a view. It creates a link to a controller action. ActionLink() is an extension method of HtmlHelper class. It returns an anchor element (a element) that contains the virtual path of the specified action. When you use ActionLink() method then you need pass three string parameter. There parameters are linkText (The inner text of the anchor element), actionName (The name of the action) and controllerName (The name of the controller). 

RenderSection() - RenderSection() is method of WebPageBase class. Scott wrote at one point, The first parameter to the "RenderSection()" helper method specifies the name of the section we want to render at that location in the layout template. The second parameter is optional, and allows us to define whether the section we are rendering is required or not. If a section is "required", then Razor will throw an error at runtime if that section is not implemented within a view template that is based on the layout file (which can make it easier to track down content errors). It returns the HTML content to render. 

RenderBody() - In layout pages, renders the portion of a content page that is not within a named section. It returns the HTML content to render. RenderBody is required, as it's what renders each view. 

The _ViewStart File 

The _ViewStart file in the Views folder contains the following content: 
 

@{

    Layout = "~/Views/Shared/_Layout.cshtml" ;

}

  This code is automatically added to all views displayed by the application. If you remove this file, you must add this line to all views. 
  
Create Controller in MVC Application 

You need to create a controller that contains action method to render view on user interface. I am going to create HomeController controller that has two action methods one is Index and another is About. Both action methods execute when request type GET and render a view on browser. So follow these steps: 

Step 1: Right click on Controllers folder under Solution Explorer after that go to "Add" and click on Controller. 

Step 2: Give the name HomeController in Controller name input and select "Empty MVC controller" from Template dropdown list. After that click on Add. 

Now you need to write the following code in HomeController.cs file 
 

using System.Web.Mvc;

 

namespace LayoutMvcApplication.Controllers

{

    public class HomeController : Controller

    {

 

        public ActionResult Index()

        {

            return View();

        }

 

        public ActionResult Index()

        {

            return View();

        }

    }

  
Create View in MVC Application 

You need to create two views (Index and About). That inherits the _Layout view via _ViewStart view so you need follow following steps. 

Step 1: Right click on Index() action method under HomeController.cs file after that click on Add View 

Step 2: Add New screen leave unchanged and click on Add 

Now you should write following code in your web application index view 
 

@{

    ViewBag.Title = "Index" ;

}

 

@section featured

{

    < section class ="featured">

        < div class ="content-wrapper">

            < hgroup class ="title">

                < h1 > @ ViewBag.Title. </ h1 >                

            </ hgroup >

            < p >

               It is featured section. That is named section in Layout template which defined by RenderSection

            </ p >

        </ div >

    </ section >    

}

It is body of Index view that renders in BodyRender. </ p        
You can follow same steps for About view and create it. 

MVC-2.jpg
You can get same design About view. You can download source code from attachment. 

Beside this code I want to share one thing that it is my maiden fifty of articles on C# Corner. 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值