mvc lecture -4 - s p sharma · asp.net mvc is an open source framework built on the top of...

16
PARASHAR TECHNOLOGIES ASP.NET 09910707562 1 www.parashartechnologies.com S.P.SHARMA MVC LECTURE -4 Layouts, RenderBody, RenderSection and RenderPage in ASP.NET MVC Layouts are used to maintain a consistent look and feel across multiple views within ASP.NET MVC application. As compared to Web Forms, layouts serve the same purpose as master pages, but offer a simple syntax and greater flexibility. Basic structure of Layout Page <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> @RenderBody() @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body> </html> In Asp.Net MVC, at application level we have _ViewStart file with in Views folder for defining the default Layout page for your ASP.NET MVC application.

Upload: vuduong

Post on 15-Nov-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

PARASHAR TECHNOLOGIES ASP.NET 09910707562

1 www.parashartechnologies.com S.P.SHARMA

MVC LECTURE -4

Layouts, RenderBody, RenderSection and RenderPage in ASP.NET

MVC

Layouts are used to maintain a consistent look and feel across multiple views within ASP.NET MVC

application. As compared to Web Forms, layouts serve the same purpose as master pages, but offer a

simple syntax and greater flexibility.

Basic structure of Layout Page

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

@Styles.Render("~/Content/css")

@Scripts.Render("~/bundles/modernizr")

</head>

<body>

@RenderBody()

@Scripts.Render("~/bundles/jquery")

@RenderSection("scripts", required: false)

</body>

</html>

In Asp.Net MVC, at application level we have _ViewStart file with in Views folder for defining the default

Layout page for your ASP.NET MVC application.

PARASHAR TECHNOLOGIES ASP.NET 09910707562

2 www.parashartechnologies.com S.P.SHARMA

Styles.Render and Scripts.Render

Style.Render is used to render a bundle of CSS files defined within BundleConfig.cs files. Styles.Render

create style tag(s) for the CSS bundle. Like Style.Render, Scripts.Render is also used to render a bundle of

Script files by rendering script tag(s) for the Script bundle.

public class BundleConfig

{

public static void RegisterBundles(BundleCollection bundles)

{

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(

"~/Scripts/jquery.unobtrusive*",

"~/Scripts/jquery.validate*"));

bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(

"~/Content/themes/base/jquery.ui.core.css",

"~/Content/themes/base/jquery.ui.resizable.css",

"~/Content/themes/base/jquery.ui.selectable.css",

"~/Content/themes/base/jquery.ui.button.css",

"~/Content/themes/base/jquery.ui.dialog.css",

"~/Content/themes/base/jquery.ui.theme.css"));

}

}

Styles.Render and Scripts.Render generate multiple style and script tags for each item in the CSS bundle

and Script bundle when optimizations are disabled.

When optimizations are enabled, Styles.Render and Scripts.Render generate a single style and script tag

to a version-stamped URL which represents the entire bundle for CSS and Scripts.

You can enable and disable optimizations by setting EnableOptimizations property of BundleTable class

to true or false with in Global.asax.cs file as shown below.

PARASHAR TECHNOLOGIES ASP.NET 09910707562

3 www.parashartechnologies.com S.P.SHARMA

protected void Application_Start()

{

//Other code has been removed for clarity

System.Web.Optimization.BundleTable.EnableOptimizations = false;

}

Sections

A section allow you to specify a region of content within a layout. It expects one parameter which is the

name of the section. If you don’t provide that, an exception will be thrown. A section in a layout page

can be defined by using the following code.

@section header{

<h1>Header Content</h1>

}

You can render above defined section header on the content page as given below:

@RenderSection("header")

By default, sections are mandatory. To make sections optional, just provides the second parameter

value as false, which is a Boolean value.

@RenderSection("header",false)

A view can define only those sections that are referred to in the layout page otherwise an exception will

be thrown.

RenderBody

RenderBody method exists in the Layout page to render child page/view. It is just like the

ContentPlaceHolder in master page. A layout page can have only one RenderBody method.

@RenderBody()

RenderPage

RenderPage method also exists in the Layout page to render other page exists in your application. A

layout page can have multiple RenderPage method.

@RenderPage("~/Views/Shared/_Header.cshtml")

PARASHAR TECHNOLOGIES ASP.NET 09910707562

4 www.parashartechnologies.com S.P.SHARMA

History of ASP.NET MVC

ASP.NET MVC is an open source framework built on the top of Microsoft .NET Framework to develop

web application that enables a clean separation of code. ASP.NET MVC framework is the most

customizable and extensible platform shipped by Microsoft.

ASP.NET MVC is a lightweight and highly testable open source framework for building highly

scalable and well designed web applications. Here is the list of released version history of ASP.NET

MVC Framework with theirs features.

ASP.NET MVC1

1. Released on Mar 13, 2009

2. Runs on .Net 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1

3. MVC Pattern architecture with WebForm Engine

4. Html Helpers

5. Ajax helpers

6. Routing

7. Unit Testing

ASP.NET MVC2

1. Released on Mar 10, 2010

2. Runs on .Net 3.5, 4.0 and with Visual Studio 2008 & 2010

3. Strongly typed HTML helpers means lambda expression based Html Helpers

4. Templated Helpers

5. Support for Data Annotations Attribute

6. Client-side validation

7. UI helpers with automatic scaffolding & customizable templates

8. Attribute-based model validation on both client and server

9. Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE

10. Areas for partitioning a large applications into modules

11. Asynchronous controllers

ASP.NET MVC3

1. Released on Jan 13, 2011

2. Runs on .Net 4.0 and with Visual Studio 2010

3. The Razor view engine

4. Improved Support for Data Annotations

5. Remote Validation

6. Compare Attribute

7. Sessionless Controller

8. Child Action Output Caching

PARASHAR TECHNOLOGIES ASP.NET 09910707562

5 www.parashartechnologies.com S.P.SHARMA

9. Dependency Resolver

10. Entity Framework Code First support

11. Partial-page output caching

12. ViewBag dynamic property for passing data from controller to view

13. Global Action Filters

14. Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding

15. Use of NuGet to deliver software and manage dependencies throughout the platform

16. Good Intellisense support for Razor into Visual Studio

ASP.NET MVC4

1. Released on Aug 15, 2012

2. Runs on .Net 4.0, 4.5 and with Visual Studio 2010SP1 & Visual Studio 2012

3. ASP.NET Web API

4. Enhancements to default project templates

5. Mobile project template using jQuery Mobile

6. Display Modes

7. Task support for Asynchronous Controllers

8. Bundling and minification

9. Support for the Windows Azure SDK

ASP.NET MVC5

1. Released on 17 October 2013

2. Runs on .Net 4.5, 4.5.1 and with Visual Studio 2013

3. One Asp.Net

4. Asp.Net Identity

5. ASP.NET Scaffolding

6. Authentication filters - run prior to authorization filters in the ASP.NET MVC pipeline

7. Bootstrap in the MVC template

8. ASP.NET Web API2

Difference between ASP.NET WebForm and ASP.NET MVC?

Asp.Net Web Forms Asp.Net MVC

Asp.Net Web Form follow a traditional event

driven development model.

Asp.Net MVC is a lightweight and follow MVC

(Model, View, Controller) pattern based

development model.

Asp.Net Web Form has server controls. Asp.Net MVC has html helpers.

Asp.Net Web Form supports view state for state

management at client side.

Asp.Net MVC does not support view state.

Asp.Net Web Form has file-based URLs means

file name exist in the URLs must have its

Asp.Net MVC has route-based URLs means URLs

are divided into controllers and actions and

PARASHAR TECHNOLOGIES ASP.NET 09910707562

6 www.parashartechnologies.com S.P.SHARMA

physically existence. moreover it is based on controller not on

physical file.

Asp.Net Web Form follows Web Forms Syntax Asp.Net MVC follow customizable syntax (Razor

as default)

In Asp.Net Web Form, Web Forms(ASPX) i.e.

views are tightly coupled to Code

behind(ASPX.CS) i.e. logic.

In Asp.Net MVC, Views and logic are kept

separately.

Asp.Net Web Form has Master Pages for

consistent look and feels.

Asp.Net MVC has Layouts for consistent look and

feels.

Asp.Net Web Form has User Controls for code

re-usability.

Asp.Net MVC has Partial Views for code re-

usability.

Asp.Net Web Form has built-in data controls and

best for rapid development with powerful data

access.

Asp.Net MVC is lightweight, provide full control

over markup and support many features that

allow fast & agile development. Hence it is best

for developing interactive web application with

latest web standards.

Asp.Net Web Form is not Open Source. Asp.Net Web MVC is an Open Source.

Adding a Model

You’ll use a .NET Framework data-access technology known as the Entity Framework to define and work

with these model classes. The Entity Framework (often referred to as EF) supports a development

paradigm called Code First. Code First allows you to create model objects by writing simple classes. (These

are also known as POCO classes, from "plain-old CLR objects.") You can then have the database created

on the fly from your classes, which enables a very clean and rapid development workflow. If you are

required to create the database first, you can still follow this tutorial to learn about MVC and EF app

development.

Adding Model Classes

In Solution Explorer, right click the Models folder, select Add, and then select Class.

PARASHAR TECHNOLOGIES ASP.NET 09910707562

7 www.parashartechnologies.com S.P.SHARMA

Enter the class name "Movie".

Add the following five properties to the Movie class:

using System;

namespace MvcMovie.Models

{

public class Movie

{

public int ID { get; set; }

public string Title { get; set; }

public DateTime ReleaseDate { get; set; }

public string Genre { get; set; }

public decimal Price { get; set; }

PARASHAR TECHNOLOGIES ASP.NET 09910707562

8 www.parashartechnologies.com S.P.SHARMA

}

}

We'll use the Movie class to represent movies in a database. Each instance of a Movie object will

correspond to a row within a database table, and each property of the Movie class will map to a column in

the table.

In the same file, add the following MovieDBContext class:

using System;

using System.Data.Entity;

namespace MvcMovie.Models

{

public class Movie

{

public int ID { get; set; }

public string Title { get; set; }

public DateTime ReleaseDate { get; set; }

public string Genre { get; set; }

public decimal Price { get; set; }

}

public class MovieDBContext : DbContext

{

public DbSet<Movie> Movies { get; set; }

}

}

The MovieDBContext class represents the Entity Framework movie database context, which handles

fetching, storing, and updating Movie class instances in a database. The MovieDBContext derives from

the DbContext base class provided by the Entity Framework.

In order to be able to reference DbContext and DbSet, you need to add the following using statement at

the top of the file:

using System.Data.Entity;

You can do this by manually adding the using statement, or you can right click on the red squiggly lines

and clickResolve, and then click using System.Data.Entity. Note: Several unused using statements have been removed. You can do this by right clicking in the file,

clickOrganize Usings, and then click Remove Unused Usings.

PARASHAR TECHNOLOGIES ASP.NET 09910707562

9 www.parashartechnologies.com S.P.SHARMA

Creating a Connection String and Working with SQL Server LocalDB

The MovieDBContext class you created handles the task of connecting to the database and

mapping Movie objects to database records. One question you might ask, though, is how to specify

which database it will connect to. You don't actually have to specify which database to use, Entity

Framework will default to using LocalDB. In this section we'll explicitly add a connection string in

the Web.config file of the application.

SQL Server Express LocalDB

LocalDB is a lightweight version of the SQL Server Express Database Engine that starts on demand and

runs in user mode. LocalDB runs in a special execution mode of SQL Server Express that enables you to

PARASHAR TECHNOLOGIES ASP.NET 09910707562

10 www.parashartechnologies.com S.P.SHARMA

work with databases as.mdf files. Typically, LocalDB database files are kept in the App_Data folder of a

web project.

SQL Server Express is not recommended for use in production web applications. LocalDB in particular

should not be used for production with a web application because it is not designed to work with IIS.

However, a LocalDB database can be easily migrated to SQL Server or SQL Azure.

In Visual Studio 2013 (and in 2012), LocalDB is installed by default with Visual Studio.

By default, the Entity Framework looks for a connection string named the same as the object context class

(MovieDBContext for this project). For more information see SQL Server Connection Strings for ASP.NET

Web Applications.

Open the application root Web.config file shown below. (Not the Web.config file in the Views folder.)

Find the <connectionStrings> element:

PARASHAR TECHNOLOGIES ASP.NET 09910707562

11 www.parashartechnologies.com S.P.SHARMA

Add the following connection string to the <connectionStrings> element in the Web.config file.

<add name="MovieDBContext"

connectionString="Data

Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated

Security=True"

providerName="System.Data.SqlClient"

/>

The following example shows a portion of the Web.config file with the new connection string added:

<connectionStrings>

<add name="DefaultConnection" connectionString="Data

Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-

20130603030321.mdf;Initial Catalog=aspnet-MvcMovie-20130603030321;Integrated

Security=True" providerName="System.Data.SqlClient" />

<add name="MovieDBContext" connectionString="Data

Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated

Security=True" providerName="System.Data.SqlClient"

/>

using System;

PARASHAR TECHNOLOGIES ASP.NET 09910707562

12 www.parashartechnologies.com S.P.SHARMA

using System.Data.Entity;

namespace MvcMovie.Models

{

public class Movie

{

public int ID { get; set; }

public string Title { get; set; }

public DateTime ReleaseDate { get; set; }

public string Genre { get; set; }

public decimal Price { get; set; }

}

public class MovieDBContext : DbContext

{

public DbSet<Movie> Movies { get; set; }

}

}

Accessing Your Model's Data from a Controller

You'll create a new MoviesController class and write code that retrieves the movie data and displays it

in the browser using a view template.

Build the application before going on to the next step. If you don't build the application, you'll get an

error adding a controller.

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller.

PARASHAR TECHNOLOGIES ASP.NET 09910707562

13 www.parashartechnologies.com S.P.SHARMA

In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then

click Add.

PARASHAR TECHNOLOGIES ASP.NET 09910707562

14 www.parashartechnologies.com S.P.SHARMA

For the Controller name enter MoviesController.

Select Movie (MvcMovie.Models) for the Model class.

Select MovieDBContext (MvcMovie.Models) for the Data context class.

Click Add. (If you get an error, you probably didn't build the application before starting adding the

controller.) Visual Studio creates the following files and folders:

A MoviesController.cs file in the Controllers folder.

A Views\Movies folder.

Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the

new Views\Movies folder.

Visual Studio automatically created the CRUD (create, read, update, and delete) action methods and

views for you (the automatic creation of CRUD action methods and views is known as scaffolding). You

now have a fully functional web application that lets you create, list, edit, and delete movie entries.

PARASHAR TECHNOLOGIES ASP.NET 09910707562

15 www.parashartechnologies.com S.P.SHARMA

PARASHAR TECHNOLOGIES ASP.NET 09910707562

16 www.parashartechnologies.com S.P.SHARMA