ASP.NET MVC - Model-View_lab06
ASP.NET MVC - Model-View_lab06
NET MVC
Tran Khai Thien
Introduction
First, you will learn about the Model in ASP.NET MVC framework.
Model represents domain specific data and business logic in MVC architecture.
It maintains the data of the application. Model objects retrieve and store
model state in the persistance store like a database.
Model class holds data in public properties. All the Model classes reside in the
Models folder in MVC folder structure.
Adding New Model
Open our first MVC project created in previous step in the Visual Studio. Right click
on Models folder -> Add -> click on Class..
In the Add New Item dialog box, enter class name 'Student' and click Add.
Adding a New Model
This will add new Student class in model folder. Now, add Id, Name, Age properties
as shown below.
View in ASP.NET MVC
View is a user interface. View displays data from the model to
the user and also enables them to modify the data.
ASP.NET MVC views are stored in Views folder. Different
action methods of a single controller class can render
different views, so the Views folder contains a separate
folder for each controller with the same name as controller,
in order to accommodate multiple views.
For example, views, which will be rendered from any of the
action methods of HomeController, resides in Views > Home
folder. In the same way, views which will be rendered from
StudentController, will resides in Views > Student folder as
shown below.
Adding a New View
We will create a view, which will be rendered from Index method of
StudentContoller. So, open a StudentController class -> right click inside Index
method -> click Add View.
Adding a New View
Select the scaffolding template. Template dropdown will show default templates
available for Create, Delete, Details, Edit, List or Empty view. Select "List"
template because we want to show list of students in the view.
Adding a New View
Now, select Student from the Model class dropdrown. Model class dropdown
automatically displays the name of all the classes in the Model folder. We have
already created Student Model class in the previous section, so it would be
included in the dropdown.
Adding a New View
Check "Use a layout page" checkbox and select
_Layout.cshtml page for this view and then
click Add button. We will see later what is
layout page but for now think it like a master
page in MVC.
This will create Index view under View ->
Student folder as shown.
Adding a New View
The following code snippet shows an
Index.cshtml created above.
Points to Remember
View is a User Interface which displays data and handles user interaction.
Views folder contains separate folder for each controller.
ASP.NET MVC supports Razor view engine in addition to traditional .aspx engine.
Razor view files has .cshtml or .vbhtml extension.
Integrating Controller, View and Model:
We have already created StudentController, model and view in the previous sections,
but we have not integrated all these components in-order to run it.
The following code snippet shows Student Controller and Student Model class and view
created in the previous sections.
Integrating Controller,
View and Model
Loop
Razor Syntax
Model:
Use @model to use model object anywhere in the view.
Razor Syntax
Declare Variables:
Declare a variable in a code block enclosed in brackets and then use those variables
inside html with @ symbol.
Razor Syntax
Points to Remember:
• Use @ to write server side code.
• Server side code block starts with @{* code * }
• Use @: or <text></<text> to display text from code block.
• if condition starts with @if{ }
• for loop starts with @for
• @model allows you to use model object anywhere in the view.
HTML Helpers
HtmlHelper class generates html elements using the model class object in razor view. It
binds the model object to html elements to display value of model properties into html
elements and also assigns the value of the html elements to the model properties while
submitting web form. So always use HtmlHelper class in razor view instead of writing html
tags manually.
The following figure shows the use of HtmlHelper class in the razor view.
HTML Helpers
The following table lists HtmlHelper methods and html control each
method generates.
<!DOCTYPE html>
<html>
<head>
HTML Helpers <meta charset="utf-8"/>
<meta name="viewport" content="width=device-
The following table lists HtmlHelper
width"/>
methods and html control each
<title>Index</title>
method generates.
<link href="/Content/site.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.5.3.js"></script>
@Html.ActionLink("Login","Index" </head>
,"Login") <body>
<h2>Index</h2>
<form action="/PersonDetails/index" method="post">
@Html.ActionLink("Link Text", </form>
<div>
"ActionName", <a href="/Login">Login</a>
"ControllerName") </div>
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></scri
pt>
</body>
</html>
HTML Helpers
Syntax of Basic HTML Helper Controls
Following are syntaxes of using basic html helper controls in ASP.NET MVC application.
Textbox - @Html.TextBox("UserName")
TextArea - @Html.TextArea("UserAddress")
Password - @Html.Password("UserPassword")
Hidden field - @Html.Hidden("UserID")
Checkbox - @Html.CheckBox("Check")
Radiobutton - @Html.RadioButton("gender", "Male", true)
DropdownList - @Html.DropDownList("DrpCountry", new List<SelectListItem> {
new SelectListItem { Text = "select", Value = "0" } ,
new SelectListItem { Text = "India", Value = "1" },
new SelectListItem { Text = "USA", Value = "2" } })
Listbox - @Html.ListBox("ListName", new List<SelectListItem> { new
SelectListItem { Text = "One", Value = "1" }, new
SelectListItem { Text = "Two", Value = "2" }, new
SelectListItem { Text = "Three", Value = "3" } })
DisplayName - @Html.DisplayName("Displayname")
Editor - @Html.Editor("EditID")
HTML Helpers
Now if werun above code wewill get basichtml helper result like asshownbelow
HTML Helpers
Points to Remember:
• It is advisable to use "For" extension methods for compile time type checking e.g.
TextBoxFor, EditorFor, CheckBoxFor etc.
Layout View
• 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.
• The layout view allows you to define a common site template, which can be
inherited in multiple views to provide a consistent look and feel in multiple pages
of an application. The layout view eliminates duplicate coding and enhances
development speed and easy maintenance. The layout view for the above sample
UI would contain a Header, Left Menu, Right bar and Footer sections. It contains a
placeholder for the center section that changes dynamically as shown below.
Layout View
The razor layout view has same extension as
other views, .cshtml or .vbhtml. Layout views
are shared with multiple views, so it must be
stored in the Shared folder. For example, when
we created our first MVC application in the
previous section, it also created
_Layout.cshtml in the Shared folder as shown
below.
Layout View
The following is an auto-generated _Layout.cshtml. The layout view
contains html
Doctype, head and
body as normal html,
the only difference is
call to RenderBody()
and RenderSection()
methods.
RenderBody acts like a
placeholder for other
views. For example,
Index.cshtml in the
home folder will be
injected and rendered
in the layout view,
where the
RenderBody() method
is being called. You
will learn about these
rendering methods
later in this section.
Layout View
The following is an auto-generated _Layout.cshtml. The layout view
contains html
Doctype, head and
body as normal html,
the only difference is
call to RenderBody()
and RenderSection()
methods.
RenderBody acts like a
placeholder for other
views. For example,
Index.cshtml in the
home folder will be
injected and rendered
in the layout view,
where the
RenderBody() method
is being called. You
will learn about these
rendering methods
later in this section.
Layout View
Use Layout View:
You can set the layout view in multiple ways, by using _ViewStart.cshtml or setting up path
of the layout page using Layout property in the individual view or specifying layout view
name in the action method.
_ViewStart.cshtml:
_ViewStart.cshtml is included in the Views folder by default. It sets up the default layout
page for all the views in the folder and its subfolders using the Layout property.
The following _ViewStart.cshtml in the Views folder, sets the Layout property to
"~/Views/Shared/_Layout.cshtml". So now, _layout.cshtml would be layout view of all the
views included in Views and its subfolders. So by default, all the views derived default
layout page from _ViewStart.cshtml of Views folder.
Layout View
Setting Layout property in individual view:
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.
Layout View
Specify Layout page in ActionResult method:
You can also specify which layout page to use in while rendering view from action
method using View() method.
The following example, View() method renders Index view using _myLayoutPage.cshtml.
Layout View
Rendering Methods:
ASP.NET MVC layout view renders child views using the following methods.
Method Description
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.
Layout View
The following figure illustrates the use of RenderBody and RenderSection methods.
Layout View
Create Layout View:
To create a new layout view in Visual Studio, right click on shared folder ->
select Add -> click on New Item..
In the Add New Item dialogue box, select MVC 5 Layout Page (Razor) and give
the layout page name as "_myLayoutPage.cshtml" and click Add.
Layout View
Create Layout View:
You will see _myLayoutPage.cshtml as shown below.
Layout View
Adding RenderSection in Layout: Now, add the <footer> tag with the
@RenderSection("footer",true) method along with some styling as shown below.
Please notice that we made this section as required. This means any view that uses
_myLayoutPage as its layout view must include a footer section.
Layout View
Now, let's use this _myLayoutPage.cshtml with the Index view of HomeController
(or adding a new Controller).
You can add an empty Index view by right clicking on Index action method of
HomeController and select Add View. Select Empty as a scaffolding template and
_myLayoutPage.cshtml as layout view and click Add.
Layout View
This will create Index.cshtml as shown below.
Layout View
Adding Section in View and Rendering Sections: So now, we have created Index
view that uses our _myLayoutPage.cshtml as a layout view. We will now add footer
section along with some styling because _myLayoutPage requires footer section.
Layout View
Now, run the application and you will see Index view will contain body and footer
part as shown below.
Layout View – Question?
Layout View
Points to Remember:
• The Layout view contains common parts of a UI. It is same like masterpage of ASP.NET
webforms.
• _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.
• You can set the Layout property in the individual view also, to override default layout
page setting of _ViewStart.cshtml
• Layout view uses two rendering methods: RenderBody() and RenderSection().
• RenderBody can be used only once in the layout view, whereas the RenderSection
method can be called multiple time with different name.
• RenderBody method renders all the content of view which is not wrapped in named
section.
• RenderSection method renders the content of a view which is wrapped in named section.
• RenderSection can be configured as required or optional. If required, then all the child
views must included that named section.
Partial View
Partial view is a reusable view, which can be used as a child view in multiple
other views. It eliminates duplicate coding by reusing same partial view in
multiple places. You can use the partial view in the layout view, as well as
other content views.
Partial View
For that create following items in our application: