Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Unit 3 ASP.net Mvc Notes

The document outlines a course on Microsoft .NET technologies, focusing on ASP.NET MVC, which enables students to create web applications using a structured Model-View-Controller architecture. It details the objectives and outcomes of the course, including practical skills in web application development, database applications, and API design. The document also explains the components of ASP.NET MVC, such as controllers, views, and models, and their roles in managing application complexity and improving development efficiency.

Uploaded by

paxawek190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit 3 ASP.net Mvc Notes

The document outlines a course on Microsoft .NET technologies, focusing on ASP.NET MVC, which enables students to create web applications using a structured Model-View-Controller architecture. It details the objectives and outcomes of the course, including practical skills in web application development, database applications, and API design. The document also explains the components of ASP.NET MVC, such as controllers, views, and models, and their roles in managing application complexity and improving development efficiency.

Uploaded by

paxawek190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

 Objective:

 Net Technologies are blend of technologies supported by


Microsoft .Net Framework that allows user to create various
applications. Students will be able to work with various
technologies provided by Microsoft .NET platform.
Course  Outcomes:
Objective &  After completion of this course, student will be able to:
Outcomes  To Review the components of .Net Framework
 To practice Web based application
 To create web applications using MVC framework
 To practice basic database application using ADO.net
 To designing, developing, and deploying APIs
Unit - 3
ASP.NET MVC
Prof. Ravikumar Natarajan
Department of Computer Engineering
 Introduction to ASP.NET MVC
 MVC Architecture Overview
 Controllers
 Razor Views
 LayoutView
Contents  PartialView
 Models
 HTML helpers
 Action Filters
 Model Validation
 URLs and Routing
 Model-View-Controller (MVC) is a framework for
developing applications which have become so popular
these days.
 Gone are the days when developers would go for ASP.NET
to create applications from scratch.
 MVC is a Model Controller View Pattern and using it in
Introduction to ASP.NET is why we term it as ASP.NET MVC.
ASP.NET MVC  The basic need of introducing MVC was to make complex
application development easy.
 This design pattern is a lightweight framework which is
integrated with various features such as master pages and
membership based authentication. It is defined in the
System.Web.Mvc assembly.
 MVC focusses on Separation of Concerns.
Introduction to
ASP.NET MVC
 The purpose of MVC is to separate the content from the
presentation and data processing from content.
 One thing that MVC has done is to separate the view
from the code i.e., unlike Web Forms where “*.aspx” is
attached to “*.aspx.cs” here in MVC View is a separate
Introduction to entity entirely.
ASP.NET MVC  ASP.NET MVC is stateless. In this we do not pass
requests to the page like Web Forms. But we talk to the
controller.
 The Controller handles the request and fetches the
desired data from the model and transfers the data to
the view.
 The View is used to display the data to the end user.
 There are three basic components in ASP.NET MVC:
 Model
 View
 Controller
 Model
 This is the business layer. It helps retrieve data from the
Introduction to database. These are simple class files that contain the
properties.
ASP.NET MVC
 View
 This component is responsible for displaying data on the
screen. In MVC we use Razor Syntax. The extension of the
view has “*.cshtml” instead of “.aspx” which we have used in
ASP.NET in the past.
 Controller
 It handles input control. All the user interaction is done
through Controller. A Controller is nothing but a class file that
contains the methods.
Introduction to
ASP.NET MVC
 MVC helps to maintain a pretty good URL that is readable to
the user.
 In MVC the URL has specific meaning which we will
understand now.
 The following is the structure that explains how?
ASP.NET MVC
 http://www.sitename.com/ControllerName/ActionName/Id
URL Structure
 URL is in MVC.
 Controller Name is passed after the site name followed by the
Action Name present in the controller.
 And if there is an Id we have to specify the Id as well, though it
is optional.
 Find this, http://www.dummywebsite.com/Products/View/1
 In the preceding URL “Products” is the controller and View is
the name of the ActionResult method that accepts an ID that
has a value “1” passed in the URL.
ASP.NET MVC  Comparing, http://www.dummysite.com/Products.aspx?id=1
URL Structure URL to the traditional Web Forms had it been made in the
older version would be something like it.
 ASP.NET MVC URLs are much more user friendly. Microsoft
has released many versions of ASP.NET MVC of which MVC 6
is the latest one.
How MVC
Works?

 The request goes to controller.


 Controller fetches the data from the model and passes this
data to the View.
 The view displays the data to the end user.
MVC
Architecture
Overview
 It manages application complexity by dividing an
application into the model, view and controller.
 It does not use view state or server-based forms. This
makes the MVC framework ideal for developers who want
Advantages of full control over the behavior of an application.
ASP.NET MVC  It provides better support for test-driven development.
Pattern  It is suitable for large scale developer team and web
applications.
 It provides high degree of control to the developer over the
application behavior.
 Controller is a class that handles user requests. It retrieves
data from the Model and renders view as response.
 The ASP.NET MVC framework maps requested URLs to the
classes that are referred to as controllers. Controller
processes incoming requests, handle user input and
interactions and executes appropriate business logic.
Controller  The file format will be .cs file
 Inherited from Controller class (go to definitions)
 It Resides in controller folder
 It has controller convention in name
 Controllers Handle incoming request and get data from
model and provide data to view.
 The ControllerBase class is a base class for all controller
classes. It provides general MVC handling. A controller
mainly performs the following tasks.
• It locates for the appropriate action method to call and
validate.
Controller • It gets the values to use as the action method's arguments.
• It handles all errors that might occur during execution of
the action.
• It uses the WebFormViewEngine class for rendering
ASP.NET page.
We can create controller for the application by adding a new
item into the controller folder. Just right click on the controller
folder and click add -> controller as given below.

Controller
// MusicStoreController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
Controller
public class MusicStoreController : Controller
{
// GET: MusicStrore
public ActionResult Index()
{
return View();
} } }
 Create ASP.NET Web Application (.NET Framework) ->
select Empty -> MVC check box and create project.

Controller
Demo
 HomeController.cs

using System.Web.Mvc;

namespace WebApplication8.Controllers
{
public class HomeController : Controller
Controller {
public string Index()
Demo {
return "Hello";
}

public string Name()


{
return "Ravi";
}
}
}
 HomeController.cs

using System.Web.Mvc;

namespace WebApplication8.Controllers
{
public class HomeController : Controller
Controller {
public string Index()
Demo {
return "Hello";
}

public string Name()


{
return “RK KEYNOTES";
}
}
}
Action Methods?

 A method inside controller is called as Action Method.


 Default return type of Action method is ActionResult
 Only public method can be accessed from http request
 By default all action methods are GET
Controller  Action methods can return View, File, Partial View,
Demo JSON, etc.
Output
Controller  RouteConfig Demo
Demo
 EmployeeController
using System.Web.Mvc;

namespace WebApplication8.Controllers
{
public class EmployeeController : Controller
{

//public string EmployeeProfile(int id)


//{
// return "profile";
//}

public string EmployeeProfile(int id)


{

Controller string profile = string.Empty;


if (id == 1)
{

Demo }
profile = "EMP 1";

else if (id == 2)
{
profile = "EMP 2";
}
else
{
profile = "No profile";
}
return profile;
}
public string Address(int id, string division) {
return "id= " + id + "division= " + division;
}
}
}
 EmployeeController

Controller Parameters in action method


Demo
 The MVC View is a standard HTML page that may
contain script. It is used to create web pages for the
application. Unlike ASP.NET Web Pages, MVC Views
are mapped to the action and then controller renders
the view to the browser.
 MVC has certain conventions for project structure. The
view file should be located in the subdirectory of View
View in MVC folder.
 MVC uses Razor view engine so that we can write
server side code in HTML as well. Let's create a view
and execute it to the browser.
 File extension is .cshtml (c sharp + html)
 View is UI of application and it supports HTML
 Razor View Engine is a markup syntax which helps us to
write HTML and server-side code in web pages using
View in MVC C# or VB.Net.
 It is server-side markup language however it is not at all
a programming language.
 WHY VIEW IS REQUIRED?
 To make application interactive
View in MVC  Easy to use
 To use html and other client side framework
 Step 1
 Create MVC project
 Step 2
 Add HomeController and
 EmployeeController
View Demo
 Step 3
 Check the view folder,
View Demo  You can see two folders in the
Name of controllers.
 Step 4
 Right click on Home in views folder
 Add -> view

View Demo
 Step 5
 Open Index.cshtml

<!DOCTYPE html>

<html>
<head>
<meta name="viewport"
View Demo content="width=device-width" />
<title>Index</title>
</head>
<body>
<div> <h1>Hi, Home Controller and Index
method </h1>
</div>
</body>
</html>
 Step 6
 In HomeController.cs

using System.Web.Mvc;

namespace ViewDemo.Controllers
{
public class HomeController : Controller
View Demo {
// GET: Home
public ActionResult Index()
{
return View();
}
public ViewResult AboutUs()
{
return View();
}
}
}
 Step 6
 Do same in EmployeeController.cs and run

View Demo
 Points

 In MVC, browser cannot call view directly.


 Controller will perform it.
View Demo  Browser doesn’t know one is calling view or
something else. Because it is a job of Action Method.
 Browser will dispay the content via view.
 Step 7
 Index.cshtml – Create Hyperlink

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
View Demo </head>
<body>
<div> <h1>Hi, Home Controller and Index method </h1>
</div>
<div>
<a href="/Home/AboutUs">Home - AboutUs</a>
<a href="/Employee/Index">Employee - Index</a>
<a href="/Employee/AboutUs">Employee - AboutUs</a>
</div>
</body>
</html>
If the view file is not available, the controller will try to check all the possibilities and
throw this error.

View Demo
 A model is a class that contains the business logic of the
application. It also used for accessing data from the
database.
 The model class does not handle directly input from the
Model in MVC browser. It does not contain any HTML code as well.
 Models are also refers as objects that are used to
implement conceptual logic for the application.
 A controller interacts with the model, access the data,
perform the logic and pass that data to the view.
 To add the model, just right click on the Model folder of the
project and then follow this sequence Model->Add->New
Item->Visual C#->Code->Class.
// Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
Model in MVC using System.Web;
public class Student {

public int StudentId { get; set; }

public string StudentName { get; set; }

public int Age { get; set; }


}
 To add the model, just right click on the Model folder of the
project and then follow this sequence Model->Add->New
Item->Visual C#->Code->Class.
// Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
Model in MVC using System.Web;
public class Student {

public int StudentId { get; set; }

public string StudentName { get; set; }

public int Age { get; set; }


}
The model class can be used in the view to populate the data, as well
as sending data to the controller.
 To add the model, just right click on the Model folder of the
project and then follow this sequence Model->Add->New
Item->Visual C#->Code->Class.
// Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
Model in MVC using System.Web;
public class Student {

public int StudentId { get; set; }

public string StudentName { get; set; }

public int Age { get; set; }


}
The model class can be used in the view to populate the data, as well
as sending data to the controller.
Integrate/Bind
Model, View
and Controller
//Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCDemo.Models
Model {
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
}
//StudentController.cs
using System.Web.Mvc;

namespace MVCDemo.Controllers
{
public class StudentsController : Controller
Controller {
// GET: Students
public ActionResult Index()
{
return View();
}
}
}
<div class="form-group">
@model MVCDemo.Models.Student @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-
md-2" })
@{ <div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-
ViewBag.Title = "Index";
control" } })
} @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
</div>
<h2>Index</h2> </div>
<div class="form-group">
@using (Html.BeginForm()) <div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
{ </div>
</div>
@Html.AntiForgeryToken()
</div>
}

View <div class="form-horizontal">

<h4>Student</h4>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<hr />

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

<div class="form-group">

@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

</div>

</div>
Output
 Razor is a standard markup syntax that allows us to embed
server code into the web pages.
 It uses its own syntax and keywords to generate view.
 If there is server code in the web page, server executes that
ASP.NET code first then send response to the browser. It allows us to
Razor View perform logical tasks in the view page.
 We can create expressions, loops and variables in the view
page.
 It has simplified syntax which is easy to learn and code. This
file extension is .cshtml.
 Razor code blocks are enclosed in @{ ... }
 Inline expressions (variables and functions) start with @
 Code statements end with semicolon
 Variables are declared with the var keyword
 Strings are enclosed with quotation marks
 C# code is case sensitive
Razor Syntax  C# files have the extension .cshtml
Rules
@{var price=60;}
<html>
<body>
@if (price>50)
{
<p>The price is greater than 50.</p>
}
</body>
 Compact: Razor syntax is compact, enabling you to
minimize the number of characters and keystrokes
required to write code.
Razor  Easy to Learn: Razor syntax is easy to learn where you can
Characteristics use your familiar language C# or Visual Basic.
 Intellisense: Razor syntax supports statement completion
within Visual Studio.
<h2>Index</h2>
<h2>@DateTime.Now.ToShortDateString()</h2>

Razor View @{
Demo var d = DateTime.Now.ToShortDateString();
var m = "Hello";
}
<h2> Date is: @d </h2>
<h3> @m</h3>
@if(DateTime.IsLeapYear(DateTime.Now.Year) )
{
@DateTime.Now.Year @:is a leap year.
}
else {
@DateTime.Now.Year @:is not a leap year.
}
Razor View
//
Demo @for (int i = 0; i < 5; i++) {
@i.ToString() <br />
}
//
<ul> @foreach (var x in Request.ServerVariables) {
<li>@x</li>} </ul>
@{
var totalMessage = "";

var num1 = Request["text1"];


Accept User var num2 = Request["text2"];
Input var total = num1.AsInt() + num2.AsInt();
totalMessage = "Total = " + total;
}
<html>
<body style="background-color: beige; font-family: Verdana,
Arial;">
<form action="" method="post">
<p>
<label for="text1">First Number:</label><br>
<input type="text" name="text1" />
</p>
Accept User <p>
Input <label for="text2">Second Number:</label><br>
<input type="text" name="text2" />
</p>
<p><input type="submit" value=" Add " /></p>
</form>
<p>@totalMessage</p>
</body>
</html>
Output
 Razor is one of the view engines supported in ASP.NET
MVC.
 Razor allows you to write a mix of HTML and server-side
code using C# or Visual Basic.
 Razor code will be executed before HTML.
Points  It is server-side markup language however it is not at all a
programming language.
 Razor view is similar to APSX. ASPX files have a
dependency on the ASP.NET runtime to be available to
parse and execute those ASPX files. Razor has no such
dependencies.
 The ViewBag in ASP.NET MVC is used to transfer
temporary data (which is not included in the
model) from the controller to the view.
What is View  ViewBag only transfers data from controller to
Bag? view, not visa-versa.
 ViewBag values will be null if redirection occurs.
 An application may contain a specific UI portion that
remains the same throughout the application, such as
header, left navigation bar, right bar, or footer section.
 ASP.NET MVC introduced a Layout view which
Layout View contains these common UI portions so that we don't
have to write the same code in every page.
 The layout view is the same as the master page of the
ASP.NET webform application.
 An application may contain a specific UI portion that
remains the same throughout the application, such as
header, left navigation bar, right bar, or footer section.
 ASP.NET MVC introduced a Layout view which
contains these common UI portions so that we don't
have to write the same code in every page.
 The layout view is the same as the master page of the
ASP.NET webform application.
Layout View
 You can create a layout view in any folder under the Views
folder. However, it is recommended to create all the layout
views in the Shared folder for easy maintenance purpose.
 To create a new layout view in Visual Studio, right-click on
the Shared folder -> select Add -> click on New Item. This
Create Layout will open the Add New Item popup, as shown below.
View  In the Add New Item dialogue box, select MVC 5 Layout
Page (Razor) template, and specify a layout view name as
_myLayoutPage.cshtml and click Add to create it as shown
below.
 Prefixing the underscore _ before layout view name is a
common naming convention in ASP.NET MVC.
Layout View
Demo
_myLayoutPage.cshtml

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
Layout View <title>@ViewBag.Title</title>
</head>
Demo <body>
<div>
@RenderBody()
</div>
</body>
</html>
_myLayoutPage.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
Layout View @Scripts.Render("~/bundles/modernizr")
</head>
Demo <body>
<div>
@RenderBody()
</div>
<footer class="panel-footer">
@RenderSection("footer", true)
</footer>
</body>
</html>
Layout View
Demo
@{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_myLayoutPage.cshtml";
}

<h2>Index</h2>
<div class="row">
Layout View <div class="col-md-4">
Demo <p>This is body.</p>
</div>
@section footer{
<p class="lead">
This is footer section.
</p>
}
</div>
 A partial view is a reusable portion of a web page.
 It is .cshtml or .vbhtml file that contains HTML code.
 It can be used in one or more Views or Layout Views.
 You can use the same partial view at multiple places
Partial View and eliminates the redundant code.

 Let's create a partial view for the following menu, so


that we can use the same menu in multiple layout
views without rewriting the same code everywhere.
Partial View
Partial View
 Create a New Partial View
 To create a partial view, right click on the Shared
folder -> click Add -> click View

Partial View
 _MenuBar.cshtml
Cut the layout code and paste in _MenuBar
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-
target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
Partial View @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new {
@class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
</div>
</div>
 You can render the partial view in the parent view using
the HTML helper methods:

Rendering  @html.Partial(),
 @html.RenderPartial(), and
Partial View
 @html.RenderAction().
 @html.Partial()
 The @Html.Partial() method renders the specified
partial view. It accepts partial view name as a string
parameter and returns MvcHtmlString. It returns an
HTML string, so you have a chance of modifying the
HTML before rendering.
Rendering Now, include _MenuBar partial view in _Layout.cshtml using
Partial View @html.Partial("_MenuBar")
 @html.Partial()

Rendering
Partial View
 @html.RenderPartial()
 The @html.RenderPartial() method is the same as the
@html.Partial() method except that it writes the
resulted HTML of a specified partial view into an HTTP
response stream directly. So, you can modify it's HTML
before render.
 The RenderPartial() method returns void, so a
Rendering semicolon is required at the end, and so it must be
enclosed within the @{ }.
Partial View
<body>
@{
Html.RenderPartial("_MenuBar");
}
 @html.RenderAction()
 The @html.RenderAction() method executes the
specified action method and renders the result. The
specified action method must be marked with the
[ChildActionOnly] attribute and return the
PartialViewResult using the PartialView() method.
 To render a partial view using the RenderAction()
method, first create an HttpGet action method and
apply the ChildActionOnly attribute.
Rendering  In Home controller add the below code:
Partial View
public class HomeController : Controller
{
[ChildActionOnly]
public ActionResult RenderMenu()
{
return PartialView("_MenuBar");
}
}
 @html.RenderAction()
 In Layout, include below code

<body>
Rendering @{
Html.RenderAction("RenderMenu", "Home");
Partial View }
 The HtmlHelper class renders HTML controls in the
razor view.
 It binds the model object to HTML controls to display the
value of model properties into those controls and also
HTML Helpers assigns the value of the controls to the model properties
while submitting a web form.
 So always use the HtmlHelper class in razor view instead of
writing HTML tags manually.
HTML Helpers
 @Html is an object of the HtmlHelper class. (@ symbol is
used to access server-side object in razor syntax).
 Html is a property of the HtmlHelper class included in base
class of razor view WebViewPage.
 The ActionLink() and DisplayNameFor() are extension
methods included in the HtmlHelper class.
Extension Method Strongly Typed Method Html Control
Html.ActionLink() NA <a></a>
Html.TextBox() Html.TextBoxFor() <input type="textbox">
Html.TextArea() Html.TextAreaFor() <input type="textarea">
Html.CheckBox() Html.CheckBoxFor() <input type="checkbox">
Html.RadioButton() Html.RadioButtonFor() <input type="radio">
Html.DropDownList() Html.DropDownListFor() <select>
<option>
</select>
HtmlHelper Html.ListBox() Html.ListBoxFor() multi-select list box: <select>
Methods Html.Hidden() Html.HiddenFor() <input type="hidden">
Html.Password() Html.PasswordFor() <input type="password">
Html.Display() Html.DisplayFor() HTML text: ""
Html.Label() Html.LabelFor() <label>
Html.Editor() Html.EditorFor() Generates Html controls based
on data type of specified
model property e.g. textbox
for string property, numeric
field for int, double or other
numeric type.
 <input type="text" name="fname" id="fname" />
 @Html.TextBox(“fname”, “RK KEYNOTES”)
 @Html.TextBox("fn", "RAVI", new { style = "background-
color:Red; color:White; font-weight:bold", title="Enter
HTML Helper Name"})
Demo  @Html.Label("firstname", "First Name")
 @Html.Password("Password")
 @Html.TextArea("Comments","",5,20,null)
 @Html.Hidden("ID")
 In CSS file:
 .greenbox{
 background-color:Red;
 color:White;
HTML Helper  font-weight:bold
Demo }
 In VIEW file:
 <link href="~/Content/Site.css" rel="stylesheet" />
 @Html.TextBox("fname", "RK", new { @class = "greenbox"})
 In ASP.NET MVC application, the controller defines
action methods that are used to handle user requests
and render view as the response. A controller can have
any number of actions.

 A user request can be any of like: entering URL into the


MVC Actions browser, clicking a link or submitting a form.

 The MVC application uses the routing rules that are


defined in the Global.asax.cs file. This file is used to parse
the URL and determine the path of the controller. Now,
controller executes the appropriate action to handle the
user request.
 ActionResult Return Type
 The ActionResult class is the base class for all action
results. Action methods return an instance of this class.
There can be different action result types depending on the
task that the action is implementing.
Action Result Helper Method Description
ViewResult View It is used to render a view as a Web page.

PartialViewResul PartialView It is used to render a partial view.


t

MVC Actions RedirectResult Redirect It is used to redirect to another action method by using its URL.

RedirectToRoute RedirectToAction It is used to redirect to another action method.


Result RedirectToRoute
ContentResult Content It is used to return a user-defined content type.

JsonResult Json It is used to return a serialized JSON object.

JavaScriptResult JavaScript It is used to return a script that can be executed on the client.

FileResult File It is used to return binary output to write to the response.

EmptyResult (None) It represents a return value that is used if the action method
must return a null result.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class MusicStoreController : Controller
{
// GET: MusicStrore
Adding an public ActionResult Index()
{
Action method return View();
}
public string Welcome()
{
return "Hello, this is welcome action message";
}
}
}
To access the welcome action method, execute the application then access it by
using MusicStore/Welcome URL. It will produce the following output.
 Action parameters are the variables that are used to retrieve user requested
values from the URL.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class MusicStoreController : Controller
Action Method {
Parameters // GET: MusicStrore
public ActionResult Index()
{
return View();
}
public string ShowMusic(string MusicTitle)
{
return "You selected " + MusicTitle + " Music";
}
}
} In URL, we have to pass the parameter value. So, we are doing it by this
URL localhost:port-no/MusicStore/ShowMusic?MusicTitle=Classic.
 Action selectors are attributes that are applied on
action methods of a controller. It is used to select
correct action method to call as per the request. MVC
provides the following action selector attributes:

ASP.NET MVC  ActionName


Action  This attribute allows us to specify a different name for
the action method. It is useful when we want to call
Selectors action by different name.
 ActionVerbs
 ASP.NET MVC provides action verbs that are applied
on the action methods and works for HttpRequest
methods.
//MusicStoreController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
Action Name public class MusicStoreController : Controller
{
[ActionName("store")]
public ActionResult Index()
{ // store.cshtml
@{
return View(); ViewBag.Title = "store";
} }
<h2>Hello, This is Music store.</h2>
}
}
Action Name
 ActionVerbs
 ASP.NET MVC provides action verbs that are applied on the
action methods and works for HttpRequest methods.
• HttpPost
• HttpGet
Action Verbs • HttpPut
• HttpDelete
• HttpOptions
• HttpPatch
// MusicStoreController.cs
using System; using System.Collections.Generic; using System.Linq;
using System.Web; using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class MusicStoreController : Controller
{
[HttpGet]

ActionVerbs public ActionResult Index()


{
return View();
}
[HttpPost]
public ActionResult Welcome()
{
return View();
} } }
// index.cshtml
<div class="jumbotron">
<h2>Welcome to the music store.</h2>
</div>

ActionVerbs
 The MVC framework provides the filter attribute so that we
can filter the user requests. We can apply it to an individual
action or an entire controller.
 ASP.NET MVC Filter is a custom class where you can write
custom logic to execute before or after an action method
ASP.NET executes.
MVC- Filters  Filters can be applied to an action method or controller in a
declarative or programmatic way.
 Declarative means by applying a filter attribute to an action
method or controller class and programmatic means by
implementing a corresponding interface.
Filter Type Description Built-in Filter Interface
Authorization Performs authentication [Authorize], IAuthorizationFilter
filters and authorizes before [RequireHttps]
executing an action
method.
Action filters Performs some operation IActionFilter
before and after an action
ASP.NET method executes.

MVC- Filters Result filters Performs some operation [OutputCache] IResultFilter


before or after the
execution of the view.
Exception Performs some operation [HandleError] IExceptionFilter
filters if there is an unhandled
exception thrown during
the execution of the
ASP.NET MVC pipeline.
// MusicStoreController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
OutputCache public class MusicStoreController : Controller
Example {
[OutputCache(Duration =10)]
public ActionResult Index()
{
return View(); // index.cshtml
<h4>
}
@{
} Response.Write( DateTime.Now.ToString("T"));
} }
</h4>
 It produces the following output and cache that for 10
seconds. It will not change before 10 seconds even we
refresh the web page again and again.

OutputCache
Example
// MusicStoreController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
Authorize public class MusicStoreController : Controller

Example {
[Authorize]
public ActionResult Index()
{
return View();
}
}
}
 Validation of user input is necessary task for the
application programmer. An application should allow
only valid user input so that we get only desired
MVC information.
Validation
 ASP.NET MVC framework provides built-in annotations
that we can apply on Model properties. It validates
input and display appropriate message to the user.
Attribute Usage
Required Specifies that a property value is required.
StringLength Specifies the minimum and maximum length of characters that are
allowed in a string type property.
Range Specifies the numeric range constraints for the value of a property.
RegularExpres Specifies that a property value must match the specified regular
sion expression.
MVC CreditCard Specifies that a property value is a credit card number.

Validation CustomValidat
ion
Specifies a custom validation method that is used to validate a property.

EmailAddress Validates an email address.


FileExtension Validates file name extensions.
MaxLength Specifies the maximum length of array or string data allowed in a
property.
MinLength Specifies the minimum length of array or string data allowed in a property.
Phone Specifies that a property value is a well-formed phone number.
public class Student {

public int StudentId { get; set; }

DataAnnotation [Required]
Attributes public string StudentName { get; set; }

[Range(10, 20)]
public int Age { get; set; } }
//model
namespace mvcval6m.Models
{
Validation public class Class1
{
Demo public string username { get; set; }
}
}
//controller
using System.Web.Mvc;

namespace mvcval6m.Controllers
{
Validation public class HomeController : Controller
{
Demo // GET: Home
public ActionResult Index()
{
return View();
}
}
}
//view
@model mvcval6m.Models.Class1
@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<head>
<script>
Validation
Demo function validate() {
if
(document.getElementById("txtuser").value.length == 0) {
document.getElementById("spuser").innerHTML =
"Name required";
return false;
}
}

</script>
</head>
<body>
<div>
@using (Html.BeginForm())
{
<table>
<tr><td>Enter
Name:</td><td>@Html.TextBoxFor(a => a.username, new
{id="txtuser" })</td><td><span id="spuser"></span></td></tr>

Validation <tr><td colspan="3"><input type="submit"


name="btnsubmit" value="Insert" onclick="return
Demo validate()"/></td></tr>
</table>
}

</div>

</body>
Output
 In MVC, routing is a process of mapping the browser
request to the controller action and return response back.
 Each MVC application has default routing for the default
HomeController. We can set custom routing for newly
Routing created controller.

 The RouteConfig.cs file is used to set routing for the


application.
Routing
//RouteConfig.cs
using System.Web.Mvc;
using System.Web.Routing;
namespace mvcval6m
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
Routing routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action =
"Index", id = UrlParameter.Optional }
);
} } }
 The URL pattern is considered only after the domain
name part in the URL. For example, the URL pattern
"{controller}/{action}/{id}" would look like
localhost:1234/{controller}/{action}/{id}.
 Anything after "localhost:1234/" would be considered
as a controller name.
 The same way, anything after the controller name
URL Pattern would be considered as action name and then the value
of id parameter.
URL Controller Action Id
http://localhost/home HomeController Index null

URL Pattern http://localhost/home/index/123 HomeController Index 123

http://localhost/home/about HomeController About null


 Introduction to ASP.NET MVC
 MVC Architecture Overview
 Controllers
 Razor Views
 LayoutView
Summary  PartialView
 Models
 HTML helpers
 Action Filters
 Model Validation
 URLs and Routing
 Working with ADO.Net:
 ADO.Net Architecture
 Characteristics of ADO.Net
 Data Namespaces
 ADO.Net Object Model
 DataSet
 DataTable
 DataRelation
Up Next  Connection object
 Command Object
 Data Reader
 Object
 DataAdapter Object
 Data Controls (Repeater, DataList, DataGrid)
 Binding data with Crystal Report
 Performing CRUD operations

You might also like