Ebook - ASP - NET MVC-4th Edition PDF
Ebook - ASP - NET MVC-4th Edition PDF
NET MVC 5
MAHEDEE.NET
ASP.NET MVC 5
MAHEDEE.NET Page 1
Chapter 1: Introduction to ASP.NET MVC ..................................................................................................... 6
What is MVC?............................................................................................................................................ 6
Routing Example ....................................................................................................................................... 6
MVC Logic Layers ...................................................................................................................................... 7
MVC Request Response process ............................................................................................................... 7
What is View Engine?................................................................................................................................ 8
Chapter 2: Getting Started ............................................................................................................................ 8
ASP.NET MVC Design Goal ........................................................................................................................ 8
Demo: How to create first Application using ASP.NET MVC? ................................................................... 9
ASP.NET MVC Folder Structure ................................................................................................................. 9
The App_Data Folder .......................................................................................................................... 10
The Content Folder ............................................................................................................................. 10
The Controllers Folder ........................................................................................................................ 11
The Models Folder .............................................................................................................................. 12
The Views Folder ................................................................................................................................. 12
The Scripts Folder................................................................................................................................ 13
Layout.................................................................................................................................................. 14
Chapter 3: Views ......................................................................................................................................... 16
Uses of ViewBag ...................................................................................................................................... 16
What is ViewData, ViewBag and TempData? ......................................................................................... 17
Similarities between ViewBag & ViewData ........................................................................................ 17
Difference between ViewBag & ViewData ......................................................................................... 17
TempData............................................................................................................................................ 18
Layout with Razor ................................................................................................................................... 19
Configure Layout ................................................................................................................................. 20
Chapter 4: Introduction to Razor ................................................................................................................ 20
What is Razor? ........................................................................................................................................ 20
Razor Syntax ............................................................................................................................................ 21
Razor’s Programming Languages ............................................................................................................ 21
Main Razor Syntax Rules for C# .............................................................................................................. 21
How does it Work?.................................................................................................................................. 22
Uses of @ Sign ........................................................................................................................................ 22
MAHEDEE.NET Page 2
Working with Objects ............................................................................................................................. 24
If and Else Conditions .............................................................................................................................. 25
Reading User Input ................................................................................................................................. 25
Variables ................................................................................................................................................. 25
Data Types............................................................................................................................................... 26
Operators ................................................................................................................................................ 26
Converting Data Types ............................................................................................................................ 27
Chapter 5: Conditional and control statement ........................................................................................... 28
C# Loops and Arrays................................................................................................................................ 28
For Loops ............................................................................................................................................. 28
foreach Loops ...................................................................................................................................... 28
While Loops......................................................................................................................................... 29
Arrays .................................................................................................................................................. 29
C# Logic Conditions ................................................................................................................................. 30
The If Condition................................................................................................................................... 30
The Else Condition .............................................................................................................................. 30
The Else If Condition ........................................................................................................................... 30
Switch Conditions................................................................................................................................ 31
Chapter 6: JavaScript and CSS ..................................................................................................................... 32
JavaScript ................................................................................................................................................ 32
CSS........................................................................................................................................................... 33
Chapter 7: Controllers and Routes.............................................................................................................. 33
Controllers............................................................................................................................................... 33
What is Controllers?............................................................................................................................ 33
Actions and Parameters ...................................................................................................................... 34
What is Global.asax file? ......................................................................................................................... 36
Methods corresponding to events that fire on each request ............................................................. 36
Methods corresponding to events that do not fire on each request ................................................. 36
Routing .................................................................................................................................................... 37
Routing Engine .................................................................................................................................... 37
Route in ASP.NET MVC........................................................................................................................ 38
Action Results Return Type ..................................................................................................................... 42
MAHEDEE.NET Page 3
Explore to Action Result and Return Type .......................................................................................... 43
RedirectPermanent ......................................................................................................................... 43
RedirectToAction ............................................................................................................................ 43
RedirectToRoute ............................................................................................................................. 43
File ................................................................................................................................................... 44
JSON ................................................................................................................................................ 44
Chapter 8: Action Selectors and Action Filters ........................................................................................... 44
Action Selectors ...................................................................................................................................... 44
Action Filters ........................................................................................................................................... 46
Custom Action Filters .............................................................................................................................. 47
Chapter 9: Razor Template ......................................................................................................................... 49
Display List view ...................................................................................................................................... 49
Details View ............................................................................................................................................ 53
Create view ............................................................................................................................................. 54
Edit View ................................................................................................................................................. 54
Delete View ............................................................................................................................................. 55
Chapter 10: Code Expressions .................................................................................................................... 56
Malicious scripts ..................................................................................................................................... 56
Code Blocks ............................................................................................................................................. 57
Chapter 11: HTML Helpers .......................................................................................................................... 57
What is HTML Helpers ............................................................................................................................ 58
Standard HTML Helpers ...................................................................................................................... 58
HTML Links ...................................................................................................................................... 58
HTML Form Elements.............................................................................................................................. 58
Partial Views............................................................................................................................................ 61
Chapter 12: Introduction to Entity Framework .......................................................................................... 65
What is ORM? ......................................................................................................................................... 65
ADO.NET Entity Framework .................................................................................................................... 65
Benefits of Entity Framework ................................................................................................................. 65
Entity Framework Development Approach ............................................................................................ 66
Building Entity ......................................................................................................................................... 68
Creating application using ASP.NET MVC and EF................................................................................ 68
MAHEDEE.NET Page 4
Using LINQ............................................................................................................................................... 70
Filtering using LINQ ............................................................................................................................. 73
Chapter 13: Working with Data Using Entity Framework ........................................................................... 75
Listing using Scaffolding .......................................................................................................................... 75
Create or Insert using Scaffolding ........................................................................................................... 78
Performing edit using scaffolding ........................................................................................................... 80
Delete using scaffolding .......................................................................................................................... 81
Mass Assignment or Over posting .......................................................................................................... 83
Chapter 14: Annotations ............................................................................................................................. 85
Validation Annotations ........................................................................................................................... 85
Custom Validation ................................................................................................................................... 85
Chapter 15: Security in ASP.NET MVC ........................................................................................................ 86
Authentication ........................................................................................................................................ 86
Windows Authentication ........................................................................................................................ 87
Forms Authentication ............................................................................................................................. 87
Taking Control of Membership ............................................................................................................... 88
Authorization .......................................................................................................................................... 90
Seeding Membership .............................................................................................................................. 90
Cross site request forgery ....................................................................................................................... 92
OpenID and OAuth .................................................................................................................................. 92
Chapter 16: Deployment............................................................................................................................. 93
Deploying to IIS ....................................................................................................................................... 93
Deploying to Windows Azure.................................................................................................................. 93
Introduction to Unit Testing ....................................................................................................................... 93
MAHEDEE.NET Page 5
Chapter 1: Introduction to ASP.NET MVC
What is MVC?
MVC Stands for Model – View – Controller
It is Software Architectural pattern
o An architectural pattern is a general, reusable solution of a commonly occurring
problem in software architecture within a given context.
o Architectural patterns are similar to software design patterns but have a broader
scope.
It divides an application's implementation into three components
o Models, views, and controllers.
The Model represents the application core (for instance a list of database records).
The View displays the data (the database records).
The Controller handles the input.
Routing Example
If you request a page, first controller handles the request and orders an action which will serve
the request.
Action can use model to get database record.
Then action displays results to the view pages.
MAHEDEE.NET Page 6
MVC Logic Layers
MVC provides full control over HTML, CSS and JavaScript.
You can think MVC model defines web applications with 3 logic layers:
o The business layer (Model logic)
o The display layer (View logic)
o The input control (Controller logic)
The Model is the part of the application that handles the logic for the application data.
o Often model objects retrieve data (and store data) from a database.
The Controller is the part of the application that handles user interaction.
o Typically controllers read data from a view, control user input, and send input data to
the model.
The MVC separation helps you manage complex applications, because you can focus on one
aspect a time.
o For example, you can focus on the view without depending on the business logic.
o It also makes easier to test an application.
This life cycle above is defined for explanation and has omitted some technical details.
MAHEDEE.NET Page 7
What is View Engine?
View Engines are responsible for rendering the HTML from views to the browser.
The view engine template will have different syntax for implementation.
Currently there are few numbers of view engines available for ASP.NET MVC and the top four
view engines are Razor, traditional ASPX, Spark and NHaml.
Separation of Concern
o “The process of breaking a computer program into distinct features that overlap in
functionality as little as possible.” – Wikipedia
o Responsibility of Model, View and Controllers are separate
MAHEDEE.NET Page 8
Demo: How to create first Application using ASP.NET MVC?
Controllers are in the Controllers folder, Views are in the Views folder, and Models are in the
Models folder.
A typical ASP.NET MVC web application has the following folder content
Application information
o Properties
Also called project properties
Consists AssemblyInfo.cs - It consists of all of the build options for the project,
including version, company name, GUID, compilers options etc.
MAHEDEE.NET Page 9
o References
Contains libraries.
Application folders
o App_Data Folder
o Content Folder
o Controllers Folder
o Models Folder
o Scripts Folder
o Views Folder
Configuration files
o Global.asax
o packages.config
o Web.config
MAHEDEE.NET Page 10
The Controllers Folder
The Controllers folder contains the controller classes.
Controller responsible for handling user input and responses.
MVC requires the name of all controller files to end with "Controller".
MAHEDEE.NET Page 11
The Models Folder
The Models folder contains the classes that represent the application models.
Models hold and manipulate application data
MAHEDEE.NET Page 12
The Scripts Folder
The Scripts folder stores the JavaScript files of the application.
By default Visual Web Developer fills this folder with standard MVC, Ajax, and jQuery files
The files named "modernizr" are JavaScript files used for supporting HTML5 and CSS3 features
in the application.
MAHEDEE.NET Page 13
Layout
The file _Layout.cshtml represents the layout of each page in the application.
It is located in the Shared folder inside the Views folder.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title – MAHEDEE.NET</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
MAHEDEE.NET Page 14
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">@Html.ActionLink("your logo here", "Index",
"Home")</p>
</div>
<div class="float-right">
<section id="login">
@Html.Partial("_LoginPartial")
</section>
<nav>
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "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>© @DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
MAHEDEE.NET Page 15
RenderBody():
o In layout pages, renders the portion of a content page that is not within a
named section.
o It returns the HTML content to render.
o RenderBody is required, since it renders each view.
Chapter 3: Views
The View displays the data or database records
Provide user interface (UI) for the user
View stored in Views folder
There is a folder in Views for each controller
Typically, each view maps corresponding actions
Uses of ViewBag
The dynamic view data dictionary.
Dynamic Type object
ASP.NET MVC offers us ViewBag for passing data from controller to view
Example:
return View(aboutModel);
MAHEDEE.NET Page 16
}
@model TMS.Models.AboutModel
@{
ViewBag.Title = "About";
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
</hgroup>
<div>
<h2>@ViewBag.Message</h2>
<h2>@Model.Name</h2>
Location : @Model.Location
</div>
MAHEDEE.NET Page 17
ViewBag.Name = "Mahedee Hasan";
return View();
In View:
@ViewBag.Name
@ViewData["Name"]
TempData
MAHEDEE.NET Page 18
Layout with Razor
Use inherited methods to specify content areas
o RenderBody
o RenderSection
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<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>
@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>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
MAHEDEE.NET Page 19
Configure Layout
In _ViewStart.cshtml
The _ViewStart.cshtml file will execute at the start of each view's rendering.
Any code contained within the code block in this file will execute before any code in the view.
Typically, this file will set the layout template to be used by the views in the application
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
1) View\_ViewStart.cshtml
2) View\Home\_ViewStart.cshtml
3) View\Products\_ViewStart.cshtml
In Pages
@{
ViewBag.Title = "Home Page";
//Layout = null;
Layout = "~/Views/Shared/_Layout.cshtml";
}
MAHEDEE.NET Page 20
By running on the server, the code can perform complex tasks, like accessing databases.
Razor is based on ASP.NET, and designed for creating web applications.
It has the power of traditional ASP.NET markup, but it is easier to use, and easier to learn.
Razor Syntax
Razor:
<ul>
@for (int i = 0; i < 10; i++) {
<li>@i</li>
}
</ul>
PHP:
<ul>
<?php
for ($i = 0; $i < 10; $i++) {
echo("<li>$i</li>");
}
?>
</ul>
<ul>
<% for (int i = 0; i < 10; i++) { %>
<li><% =i %></li>
<% } %>
</ul>
MAHEDEE.NET Page 21
C# code is case sensitive
Razor files have the extension .cshtml or .vbhtml etc
HTML Commenting
o <!-- Single statement block -->
Razor commenting
@*@{
This is a razor commenting
}*@
C# Examples
When the server reads the page, it runs the Razor code first, finally sends the HTML page to
the browser.
The code that is executed on the server can perform tasks that cannot be done in the browser.
o Example: Accessing a server database.
Uses of @ Sign
To open a code block
Example:
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_EditLayout.cshtml";
MAHEDEE.NET Page 22
}
<ul>
@foreach (var item in rows)
{
// do something
}
</ul>
<ul>
@foreach (var item in rows)
{
if (item.Equals(x))
{
// do something
}
}
</ul>
<ul>
@foreach (var item in rows)
{
<li>
@if (item.Equals(x))
{
// do something
}
</li>
}
</ul>
@(someCondition ? x : y)
<!-- renders the value of x or y to the browser –>
To render single lines of content that contain plain text or unmatched HTML tags
MAHEDEE.NET Page 23
Example:
Example:
<table border="1">
<tr>
<th width="100px">Name</th>
<th width="100px">Value</th>
</tr>
<tr>
<td>Day</td><td>@DateTime.Now.Day</td>
</tr>
<tr>
<td>Hour</td><td>@DateTime.Now.Hour</td>
</tr>
<tr>
<td>Minute</td><td>@DateTime.Now.Minute</td>
</tr>
<tr>
<td>Second</td><td>@DateTime.Now.Second</td>
</tr>
</td>
</table>
MAHEDEE.NET Page 24
If and Else Conditions
Determine what to do based on conditions.
The common way to do this is with the if ... else statements:
@{
var txt = "";
if (DateTime.Now.Hour > 12)
{ txt = "Good Evening"; }
else
{ txt = "Good Morning"; }
}
<p>The message is @txt</p>
Example:
@{
var totalMessage = "";
if(IsPost)
{
var num1 = Request["text1"];
var num2 = Request["text2"];
var total = num1.AsInt() + num2.AsInt();
totalMessage = "Total = " + total;
}
}
Variables
MAHEDEE.NET Page 25
Examples
// Using the var keyword:
var greeting = "Welcome to mahedee.net";
var counter = 103;
var today = DateTime.Today;
Data Types
Operators
+= Increments a variable. i += 1
-= Decrements a variable. i -= 1
MAHEDEE.NET Page 26
== Equality. Returns true if values are equal. if (i==10)
MAHEDEE.NET Page 27
IsDateTime() type. myDate=myString.AsDateTime();
If you need to run the same statements repeatedly, you can program a loop.
If you know how many times you want to loop, you can use a for loop.
This kind of loop is especially useful for counting up or counting down.
Example
<html>
<body>
</body>
</html>
foreach Loops
If you work with a collection or an array, you often use a foreach loop.
A collection is a group of similar objects, and the foreach loop lets you carry out a task on each
item.
The foreach loop walks through a collection until it is finished.
The example below walks through the ASP.NET Request.ServerVariables collection. Such as
ALL_HTTP, ALL_RAW
Example
MAHEDEE.NET Page 28
<html>
<body>
<ul>
@foreach (var x in Request.ServerVariables)
{<li>@x</li>}
</ul>
</body>
</html>
While Loops
Example
<html>
<body>
@{
var i = 0;
while (i < 5)
{
i += 1;
<p>Line @i</p>
}
}
</body>
</html>
Arrays
Example
@{
string[] members = {"Mahedee", "Saiful", "Hasan", "Arif"};
int i = Array.IndexOf(members, "Saiful") + 1;
int len = members.Length;
string x = members[2-1];
}
<html>
<body>
<h3>Members</h3>
@foreach (var person in members)
MAHEDEE.NET Page 29
{
<p>@person</p>
}
<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Saiful is now in position @i</p>
</body>
</html>
C# Logic Conditions
The If Condition
Example
@{var price=50;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
</body>
</html>
Example
@{var price=20;}
@if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
MAHEDEE.NET Page 30
Example
Switch Conditions
Example
@{
var weekday = DateTime.Now.DayOfWeek;
var day = weekday.ToString();
var message = "";
}
<html>
<body>
@switch (day)
{
case "Monday":
message = "This is the first weekday.";
break;
case "Thursday":
message = "Only one day before weekend.";
break;
case "Friday":
message = "Tomorrow is weekend!";
break;
default:
message = "Today is " + day;
break;
}
<p>@message</p>
</body>
</html>
MAHEDEE.NET Page 31
Chapter 6: JavaScript and CSS
JavaScript
JavaScript is the programming language for the Web.
JavaScript is client side scripting languages
o Scripting languages are special type of programming language
o Run on different environment
o It interpreted rather compile
All modern HTML pages are using JavaScript.
JavaScript is easy to learn.
MAHEDEE.NET Page 32
Example:
<script type="text/javascript">
function myMessage()
{
alert("You have clicked a button.");
}
</script>
CSS
CSS stands for Cascading Style Sheets
CSS defines how HTML elements are to be displayed
Styles were added to HTML 4.0 to solve a problem
CSS saves a lot of work
External Style Sheets are stored in CSS files
body {
background-color: #333;
border-top: solid 10px #000;
color: #fff;
font-size: .85em;
font-family: "Segoe UI", Verdana, Helvetica, Sans-Serif;
margin: 0;
padding: 0;
}
MAHEDEE.NET Page 33
Example:
Create a Controller name HomeController as follows
return View();
}
return View();
}
return View();
}
}
ViewBag.Message = message;
return View();
}
Now if you run the application you will see in the home page – Home::Index
If you slightly modify the url like - http://localhost:25379/Home/Index/2323.
o You will see home page - Home::Index 2323
MAHEDEE.NET Page 34
The controller defines action methods.
Controllers can include as many action methods as needed.
Action methods typically have a one-to-one mapping with user interactions
Can take one or more parameter.
The method cannot be a static method.
The method cannot be an extension method.
The method cannot be a constructor, getter, or setter.
The method cannot have open generic types.
The method cannot contain ref or out parameters.
Example:
Modify About action of Home controller as follows
return View();
}
@{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
@*<h3>@ViewBag.Message</h3>
</p>
Input 1: http://localhost:14714/Home/About/
MAHEDEE.NET Page 35
Input 2: http://localhost:14714/Home/About/1
MAHEDEE.NET Page 36
Example: Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes); //Responsible for routing
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Routing
Routing plays an important role in an ASP.NET MVC Application execution flow.
It maps request URL to a specific controller action using a Routing Table.
Routing Engine
Let’s consider a url http://localhost/home/about .
How does it work in an MVC application?
How does it deliver a request?
o Yes, routing engine is responsible for this task.
So, what is routing engine?
o In MVC routing engine direct requests to controllers.
o It is a core part of asp.net.
MAHEDEE.NET Page 37
Route in ASP.NET MVC
If you click right button on “RegisterRoutes” and go to definition it will go to the RegisterRoutes
method of the RouteConfig class which is App_Start folder. Here is the RouteConfig class.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
}
}
MAHEDEE.NET Page 38
Sample Route
routes.MapRoute(
);
It means add a new route name “Default” and routing pattern must be
"{controller}/{action}/{id}"
Defaults route means, when you don’t type any controller or action in the URL, its goes to the
index action of home controller.
Example 1:
RouteConfig
routes.MapRoute("Cuisine",
"cuisine/{name}",
new {controller = "cuisine", action = "search", name = "" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
}
}
MAHEDEE.NET Page 39
}
Example 2:
Modify RouteConfig
routes.MapRoute("Cuisine",
"cuisine/{name}",
new { controller = "cuisine", action = "search", name =
UrlParameter.Optional });
//new { controller = "cuisine", action = "search", name = "" });
//new {controller = "cuisine", action = "search"});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
}
}
Example 3:
Modify RouteConfig
MAHEDEE.NET Page 40
routes.MapRoute("Cuisine",
"cuisine/{name}",
new { controller = "cuisine", action = "search", name =
UrlParameter.Optional });
//new { controller = "cuisine", action = "search", name = "" });
//new {controller = "cuisine", action = "search"});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
}
}
Test URL:
URL: http://localhost:50945/Cuisine
URL: http://localhost:50945/Cuisine/Mahedee%20hasan
URL: http://localhost:50945/Cuisine/?name=I%20am%20Mahedee
mysite/{username}/{action} ~/mysite/jatten/login
public/blog/{controller}-{action}/{postId} ~/public/blog/posts-show/123
{country}-{lang}/{controller}/{action}/{id} ~/us-en/products/show/123
products/buy/{productId}-{productName} ~/products/but/2145-widgets
MAHEDEE.NET Page 41
Action Results Return Type
Action typically returns an ActionResult
Most action methods return an instance of a class that derives from ActionResult
The ActionResult class is the base for all action results.
However, there are different action result types, depending on the task
o The most common action is to call the View method.
o The View method returns an instance of the ViewResult class, which is derived
from ActionResult.
You can create action methods that return an object of any type, such as a string, an integer, or
a Boolean value. These return types are wrapped in an appropriate ActionResult type before
they are rendered to the response stream.
The following table shows the built-in action result types and the action helper methods that
return them.
MAHEDEE.NET Page 42
Explore to Action Result and Return Type
RedirectPermanent
Example 1:
public class CuisineController: Controller
{
public ActionResult Search(string title = "Default parameter")
{
return RedirectPermanent("http://mahedee.net");
}
}
RedirectToAction
Example 1:
Example 2:
RedirectToRoute
Example 1:
MAHEDEE.NET Page 43
return RedirectToRoute("Default", new { controller = "Home", action = "About"
});
}
File
Example 1:
JSON
Example 1:
MAHEDEE.NET Page 44
AcceptVerbs
o This attribute is used when we want to execute some action when a particular HTTP
operation is performed like POST, GET, DELETE, etc. E.g.:
o HttpPost, HttpGet
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Employee employee)
{
// To Do Code Here
}
AcceptName
This attribute is used when you expose an action name with a different name than
its method name
Or you can use an action name attribute to expose two methods with the same name
as the action with different names. E.g.:
[ActionName("Modify")]
[HttpPost]
public ActionResult Edit(string departmentName)
{
// ...
}
Example 1:
[HttpGet]
public ActionResult Search()
{
return Content("This without parameter!");
}
}
MAHEDEE.NET Page 45
In this occasion second method will call. If we keep only first method and type above URL it will give
server error with resource cannot be found.
Example 2:
[ActionName("SearchResult")]
[HttpGet]
public ActionResult Search()
{
return Content("This without parameter!");
}
Action Filters
An action filter is an attribute
o You can apply to a controller action or an entire controller
o It modifies the way in which the action is executed.
Name Description
OutputCache Cache the output of a controller
ValidateInput Turn off request validation and allow dangerous input
Authorize Restrict an action to authorized users or roles
ValidateAntiForgeryToken Helps prevent cross site request forgeries (CSRF)
HandleError Can specify a view to render in the event of an unhandled exception
Example:
[OutputCache(Duration = 10, VaryByParam = "none")] //10 seconds
public ActionResult Index()
{
ViewBag.Message = DateTime.Now.ToString();
return View();
}
Example:
//[Authorize]
public class SelectorController : Controller
{
[HttpPost]
public ActionResult Search(string name = "mahedee")
{
// HtmlEncode is only meant to encode characters for display in HTML
MAHEDEE.NET Page 46
string msg = Server.HtmlEncode(name);
return Content(msg);
}
[Authorize]
//[Authorize(Roles = "Admin")]
public ActionResult Search()
{
return Content("This without parameter!");
}
}
Example:
Web.config
<system.web>
<customErrors mode="On"></customErrors>
<!--<customErrors mode="RemoteOnly"></customErrors>-->
</system.web>
Error Page
Views -> Shared->Error.cshtml
Responsible:
FilterConfig.cs
MAHEDEE.NET Page 47
public class LogAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
MAHEDEE.NET Page 48
Chapter 9: Razor Template
Example
Create a ASP.NET MVC Project. Example. RestaurantOnline
MAHEDEE.NET Page 49
},
new RestaurantReview
{
Id = 3,
Name = "Radison",
City = "Dhaka",
Country = "Bangladesh",
Rating = 10
},
new RestaurantReview
{
Id = 4,
Name = "The House of Elliot",
City = "Ghent",
Country = "Belgium",
Rating = 10
}
};
return lstRestaurantReview;
}
}
MAHEDEE.NET Page 50
o Add Controller
var model =
from r in objRestaurantReviewRepository.GetReviews()
orderby r.Country
MAHEDEE.NET Page 51
select r;
return View(model);
}
Create a View
@model IEnumerable<MvcApplication1.Models.RestaurantReview>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Latest Reviews</h2>
MAHEDEE.NET Page 52
@VirtualPath
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.Country)
</th>
<th>
@Html.DisplayNameFor(model => model.Rating)
</th>
<th></th>
</tr>
</table>
Details View
Demo Details View
Action for Details View
//
// GET: /RestaurantReviews/Details/5
MAHEDEE.NET Page 53
public ViewResult Details(int id)
{
RestaurantReview restaurantreview = context.RestaurantReviews.Single(x =>
x.Id == id);
return View(restaurantreview);
}
Create view
Demo of Create View
Actions for Create View
//
// GET: /RestaurantReviews/Create
//
// POST: /RestaurantReviews/Create
[HttpPost]
public ActionResult Create(RestaurantReview restaurantreview)
{
if (ModelState.IsValid)
{
context.RestaurantReviews.Add(restaurantreview);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(restaurantreview);
}
Edit View
Demo of Edit View
Actions for Edit View
//
// GET: /RestaurantReviews/Edit/5
MAHEDEE.NET Page 54
//
// POST: /RestaurantReviews/Edit/5
[HttpPost]
public ActionResult Edit(RestaurantReview restaurantreview)
{
if (ModelState.IsValid)
{
context.Entry(restaurantreview).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
return View(restaurantreview);
}
Delete View
Demo of Delete View
Actions for Delete View
//
// GET: /RestaurantReviews/Delete/5
//
// POST: /RestaurantReviews/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
RestaurantReview restaurantreview = context.RestaurantReviews.Single(x =>
x.Id == id);
context.RestaurantReviews.Remove(restaurantreview);
context.SaveChanges();
return RedirectToAction("Index");
}
MAHEDEE.NET Page 55
Chapter 10: Code Expressions
Malicious scripts
Also known as cross site scripts (XSS)
Scripting attack
Country = "Bangladesh",
Rating = 8
},
new RestaurantReview
{
Id = 3,
Name = "Radison",
City = "Dhaka",
Country = "Bangladesh",
Rating = 10
},
new RestaurantReview
{
Id = 4,
Name = "The House of Elliot",
City = "Ghent",
Country = "Belgium",
Rating = 10
}
};
return lstRestaurantReview;
}
MAHEDEE.NET Page 56
Test URL: http://localhost:50945/Reviews
Syntax
@item.Rating/10 @* 9/10 *@
@(item.Rating/10) @* 1 1 1 0 *@
m@item.Rating @* m@item.Rating 1 1 1 0 *@
@@item.Rating @* @item.Rating *@
Code Blocks
Output:
MAHEDEE.NET Page 57
What is HTML Helpers
HTML Helpers are used to modify HTML output
With MVC, HTML helpers are much like traditional ASP.NET Web Form controls.
Just like web form controls in ASP.NET, HTML helpers are used to modify HTML.
o But HTML helpers are more lightweight.
o Unlike Web Form controls, an HTML helper does not have an event model and a view
state.
With MVC, you can create your own helpers, or use the built in HTML helpers.
MVC includes standard helpers for the most common types of HTML elements, like HTML links
and HTML form elements.
HTML Links
The easiest way to render an HTML link 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.
Razor Syntax:
@Html.ActionLink("About this Website", "About")
There following HTML helpers can be used to render (modify and output) HTML form
elements:
MAHEDEE.NET Page 58
BeginForm()
EndForm()
TextArea()
TextBox()
CheckBox()
RadioButton()
ListBox()
DropDownList()
Hidden()
Password()
MAHEDEE.NET Page 59
Source file for HTLM Helper
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
//string firstVal = collection[1].ToString();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
MAHEDEE.NET Page 60
return View();
}
Partial Views
Partial views render portions of a page
o Reuse pieces of a view
o Html helpers – Partial and Action
o Razor partial views are still .cshtml files
MAHEDEE.NET Page 61
Create Shared->_Review.cshtml
@model MvcApplication1.Models.RestaurantReview
<tr>
<td>
@Model.Name
</td>
<td>
@Model.Rating
</td>
<td>
@Model.City
</td>
<td>
@Model.Country
</td>
</tr>
ReviewsController
MAHEDEE.NET Page 62
RestaurantReviewRepository objRestaurantReviewRepository = new
RestaurantReviewRepository();
var bestReview =
from r in objRestaurantReviewRepository.GetReviews()
orderby r.Rating descending
select r;
Example:
http://localhost:50945/Home/About etc
[ChildActionOnly]
public ActionResult BestReview()
{
http://localhost:50945/Home/About
_Review.cshtml
@model Ch11.Web.Models.RestaurantReview
<tr>
<td>
@Model.Name
</td>
<td>
@Model.Rating
</td>
<td>
@Model.City
</td>
MAHEDEE.NET Page 63
<td>
@Model.Country
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
@Html.ActionLink("Details", "Details", new { id = Model.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = Model.Id })
</td>
</tr>
@model IEnumerable<Ch11.Web.Models.RestaurantReview>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.Country)
</th>
<th>
@Html.DisplayNameFor(model => model.Rating)
</th>
<th></th>
</tr>
</table>
MAHEDEE.NET Page 64
Chapter 12: Introduction to Entity Framework
What is ORM?
ORM stands for Object-Relational-Mapping.
Is mechanism to access database object without considering data source.
There are both free and commercial packages available of ORM, although some programmers
opt to create their own ORM tools.
Compared to traditional techniques of exchange between an object-oriented language and a
relational database, ORM often reduces the amount of code that needs to be written
Disadvantages of ORM tools generally stem from the high level of abstraction obscuring what is
actually happening in the implementation code. Also, heavy reliance on ORM software has been
cited as a major factor in producing poorly designed databases
Lately, alternatives to ORMs such as Slazure (http://www.slazure.com/) have become available
o Slazure is a revolutionary .NET database client library
MAHEDEE.NET Page 65
Fig: Entity Framework architecture for accessing data
MAHEDEE.NET Page 66
Database First
If you already have a database, the Entity Framework designer built into Visual Studio can
automatically generate a data model that consists of classes and properties that correspond to
existing database objects such as tables and columns. The information about your database
structure (store schema), your data model (conceptual model), and the mapping between them is
stored in XML in an .edmx file. The Entity Framework designer provides a graphical UI that you can
use to display and edit the .edmx file.
Model First
If you don't have a database yet, you can begin by creating a model in an .edmx file by using the
Entity Framework graphical designer in Visual Studio. When the model is finished, the Entity
Framework designer can generate DDL (data definition language) statements to create the
database. As in Database First, the .edmx file stores model and mapping information.
Code First
Whether you have an existing database or not, you can use the Entity Framework without using the
designer or an .edmx file. If you don't have a database, you can code your own classes and
properties that correspond to tables and columns. If you do have a database, Entity Framework
tools can generate the classes and properties that correspond to existing tables and columns. The
mapping between the store schema and the conceptual model represented by your code is handled
by convention and by a special mapping API. If you let Code First create the database, you can use
Code First Migrations to automate the process of deploying the database to production. Migrations
can also automate the deployment of database schema changes to production when your data
model changes.
MAHEDEE.NET Page 67
Building Entity
Install package – Entity Framework (if required)
o PM> Install-Package EntityFramework
Enable Migration
o PM> Enable-Migrations -ContextTypeName RestaurantContext
Add Migration
o PM> add-migration initalMigration
Update database
o PM> Update-Database –Verbose
Create Models
MAHEDEE.NET Page 68
public class Restaurant
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public ICollection<RestaurantReview> Reviews { get; set; }
Add ConnectionString
Create Context
}
public DbSet<Restaurant> Restaurants {get; set;}
public DbSet<RestaurantReview> Reviews{get; set;}
}
Enable Migration
Update Configuration
MAHEDEE.NET Page 69
new Restaurant
{
Name = "Hotel Radison",
City = "Dhaka",
Country = "Bangladesh",
Reviews = new List<RestaurantReview>
{
new RestaurantReview{Rating = 9, Body = "Very good Food!"}
}
});
}
}
@model IEnumerable<MvcApplication3.Models.Restaurant>
@{
ViewBag.Title = "Home Page";
}
Using LINQ
LINQ stands for Language Integrated Query
Comprehension Query Syntax
MAHEDEE.NET Page 70
Extension Method Syntax
Sample Code 1
Sample Code 2
Sample Code 3
MAHEDEE.NET Page 71
public ActionResult Index()
{
var model = from r in _context.Restaurants //r is range variable
orderby r.Reviews.Average(review => review.Rating) ascending
select r;
return View(model);
}
Sample Code 4
return View(model);
}
Modified Project
MAHEDEE.NET Page 72
Name = r.Name,
City = r.City,
Country = r.Country,
CountOfReviews = r.Reviews.Count()
};
return View(model);
}
@model IEnumerable<MvcApplication3.Models.RestaurantViewModel>
@{
ViewBag.Title = "Home Page";
}
return View(model);
}
MAHEDEE.NET Page 73
RestaurantContext _context = new RestaurantContext();
return View(model);
}
Sample Example
@model IEnumerable<MvcApplication3.Models.RestaurantViewModel>
@{
ViewBag.Title = "Home Page";
}
<form method="get">
<input type="search" name="searchTerm" />
<input type="submit" value="Search by Name" />
</form>
MAHEDEE.NET Page 74
Chapter 13: Working with Data Using Entity Framework
<li>@Html.ActionLink("Restaurants","Index","Restaurant")</li>
4. Run application and Click Restaurant Links – and Add, Modify, Update & Delete
Example 2
MAHEDEE.NET Page 75
Create a ReviewController
MAHEDEE.NET Page 76
Modify the index view
@model MvcApplication3.Models.Restaurant
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.Partial("_Reviews", @Model.Reviews);
<p>
@Html.ActionLink("Create New", "Create")
</p>
@model IEnumerable<MvcApplication3.Models.RestaurantReview>
MAHEDEE.NET Page 77
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Rating)
</th>
<th>
@Html.DisplayNameFor(model => model.Body)
</th>
<th></th>
</tr>
</table>
MAHEDEE.NET Page 78
public class RestaurantReview
{
public int Id { get; set; }
public int Rating { get; set; }
public string Body { get; set; }
public int RestaurantId { get; set; }
}
[HttpGet]
public ActionResult Create(int restaurantId)
{
return View();
}
[HttpPost]
public ActionResult Create(RestaurantReview review)
{
if (ModelState.IsValid)
{
context.Reviews.Add(review);
context.SaveChanges();
return RedirectToAction("Index", new { id = review.RestaurantId });
}
return View(review);
}
Reviews->create.cshtml
@model MvcApplication3.Models.RestaurantReview
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>New Review</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Rating)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Rating)
MAHEDEE.NET Page 79
@Html.ValidationMessageFor(model => model.Rating)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Body)
@Html.ValidationMessageFor(model => model.Body)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
[HttpPost]
public ActionResult Edit(RestaurantReview review)
{
if (ModelState.IsValid)
{
context.Entry(review).State = System.Data.EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index", new { id = review.RestaurantId});
}
return View(review);
}
@model MvcApplication3.Models.RestaurantReview
@{
MAHEDEE.NET Page 80
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>RestaurantReview</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Rating)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Rating)
@Html.ValidationMessageFor(model => model.Rating)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Body)
@Html.ValidationMessageFor(model => model.Body)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id })
|@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
MAHEDEE.NET Page 81
Modify ReviewsController
o Add Following actions to ReviewsController
//
// POST: /Reviews/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
RestaurantReview review = context.Reviews.Find(id);
context.Reviews.Remove(review);
context.SaveChanges();
return RedirectToAction("Index", new { id = review.RestaurantId });
}
@model MvcApplication3.Models.RestaurantReview
@{
ViewBag.Title = "Delete";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Delete</h2>
<div class="display-label">
@Html.DisplayNameFor(model => model.Rating)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Rating)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Body)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Body)
</div>
MAHEDEE.NET Page 82
</fieldset>
@using (Html.BeginForm()) {
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "Index")
</p>
}
@model OnlineRestaurant.Models.RestaurantReview
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>RestaurantReview</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<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>
<div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-
label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class
= "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-
danger" })
</div>
MAHEDEE.NET Page 83
</div>
@*<div class="form-group">
@Html.LabelFor(model => model.Country, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Country, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Country, "", new { @class =
"text-danger" })
</div>
</div>*@
<div class="form-group">
@Html.LabelFor(model => model.Rating, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Rating, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Rating, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
MAHEDEE.NET Page 84
Prevent Mass Assignment or Overposting
o Use Exclude or Black list property like ([Bind(Exclude="Country,City")]
[HttpPost]
public ActionResult Edit([Bind(Exclude="Country")] RestaurantReview review)
{
if (ModelState.IsValid)
{
context.Entry(review).State = System.Data.EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index", new { id = review.RestaurantId});
}
return View(review);
}
[Range(1,10)]
[Required]
public int Rating { get; set; }
[StringLength(1000)]
[Display(Name="Comments")]
[DisplayFormat(NullDisplayText = "No Comments!")]
public string Body { get; set; }
Custom Validation
public class RestaurantReview : IValidatableObject
{
public int Id { get; set; }
[Range(1,10)]
[Required]
public int Rating { get; set; }
[Required]
[StringLength(1024,ErrorMessage="You cannot exceed 1024 character")]
MAHEDEE.NET Page 85
public string Body { get; set; }
[Display(Name="User Name")]
[DisplayFormat(NullDisplayText="anonymous")]
public string ReviewerName { get; set; }
public int RestaurantId { get; set; }
Authentication
When you authenticate a user, you are verifying the identity of the user.
You might need to know a user's identity because you're building an application that only
specific users should access, like a payroll system.
You cannot let just anyone poke around in the salary information.
So the first step would be identifying the user and making sure you know who they are.
MAHEDEE.NET Page 86
Windows Authentication
Forms Authentication
MAHEDEE.NET Page 87
Taking Control of Membership
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile",
"UserId", "UserName", autoCreateTables: true);
AreaRegistration.RegisterAllAreas();
MAHEDEE.NET Page 88
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FavoriteResturant { get; set; }
}
}
public DbSet<Restaurant> Restaurants {get; set;}
public DbSet<RestaurantReview> Reviews{get; set;}
public DbSet<UserProfile> UserProfiles { get; set; }
}
[Authorize]
//[InitializeSimpleMembership]
public class AccountController : Controller
{
//////////////
MAHEDEE.NET Page 89
if (ModelState.IsValid)
{
// Insert a new user into the database
using (var db = new RestaurantContext())
{
//……………
Authorization
[Authorize]
//[InitializeSimpleMembership]
public class AccountController : Controller
{
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
[Authorize(Users="mahedee,hasan")]
[Authorize(Roles="Admin,Contributor")]
Seeding Membership
MAHEDEE.NET Page 90
new Restaurant { Name = "Hotel Sonargaon", City = "Dhaka", Country =
"Bangladesh" },
new Restaurant
{
Name = "Hotel Radison",
City = "Dhaka",
Country = "Bangladesh",
Reviews = new List<RestaurantReview>
{
new RestaurantReview{Rating = 9, Body = "Very good Food!"}
}
});
SeedMembership();
}
if (!roles.RoleExists("Admin"))
{
roles.CreateRole("Admin");
}
if (membership.GetUser("ehsan", false) == null)
{
membership.CreateUserAndAccount("ehsan", "leads@123");
}
if (!roles.GetRolesForUser("ehsan").Contains("Admin"))
{
roles.AddUsersToRoles(new []{"ehsan"}, new []{"Admin"});
}
}
</system.web>
MAHEDEE.NET Page 91
Run following command in Package Manager Console
PM> Update-Database -Verbose
@if(User.IsInRole("admin"))
{
@Html.ActionLink("Create New", "Create")
}
[Authorize(Roles="Admin")]
Go to the login page and Use another service (Google) to log in.
MAHEDEE.NET Page 92
o Which is mentioned in AuthConfig class
References:
o http://openid.net/
o http://oauth.net/
o http://dotnetopenauth.net/
o https://github.com/dotnetopenauth
MAHEDEE.NET Page 93