SlideShare a Scribd company logo
1 of 148
ASP.NET MVC 5
VS2015 – EF 6
Hossein Zahed (MCP – MCTS – MCPD – MBA)
http://www.hzahed.com
Hossein.aspx@gmail.com
Introduction to ASP.NET MVC 5
• ASP.NET Overview
• Basics of MVC
• Creating a Sample Project
• Controllers
• Views
• Models
• Forms &Validations
• Razor & HTML Helpers
• Model Binder
• Bootstrap
• Scaffolding
• Ajax & jQuery
• Routes
• WebAPI
Overview
ASP.NET Overview
ASP.NET Web Forms Features
• Event DrivenTechnology
• Rich controls and tools
• Postbacks (Forms)
• ViewState (Hidden Input)
• Less Control over the HTML
• Hard toTest
• Rapid Development (RAD)
• Sophisticated Built-in Security Features
ASP.NET MVC Features
• More Control over HTML
• No Code Behind
• Separation of Concerns
• Easy toTest
• URL Routing
• Less Built-in Security Features
• No Postbacks
• NoViewStates
• NoToolbox Server Controls
Basics
Basics of MVC
Controller
View
Model
Creating a Sample Project (1)
Creating a Sample Project (2)
Creating a Sample Project (3)
Creating a Sample Project (4)
Creating a Sample Project (5)
Controller Basics
•Controllers are classes
• Derives from base System.Web.Controller class
• Generates the response to the all requests
•Actions are methods
• They are public
• Cannot be overloaded
• Cannot be static
• Returns an ActionResult
Controller Actions in Url
Controller
Controller –Types
• MVC Controllers
• Empty
• With Read/Write Actions
• WithViews, using Entity Framework
• Controllers Naming:
• Place it in Contollers Folder
• SampleController.cs
Controller – Action Parameters
•Empty (No parameter)
•QueryString Based
•string, int, double, datetime, … Single or
Multiple Parameters as
•Url Based (Convention)
•int id => Special Parameter
Controller – Action Results
• ActionResult  General
• ViewResult View (Conventions)
• PartialViewResult  PartialView
• RedirectResult  Redirect
• RedirectToRouteResult  RedirecToAction / RedirectToRoute
• ContentResult  Content (Equivalent)
• JsonResult  Json (Json.Net)
• JavaScriptResult  JavaScript (Ajax & jQuery Senarios)
• FileResult  File (MimeTypes)
• EmptyResult  (None)
View
View – Basics
•Views provide User Interface (UI)
•Visual Design of the website
•Views are HTML + CSS + JavaScript + C# codes
combined
•Views are not directly accessible!
•Controllers pass data to Views to present it to the
user.
View – Naming Conventions
•In Home Controller:
public ActionResult MyPage()
{
…
returnView(); //Searches forViews/Home/MyPage.cshtml
returnView(“OtherPage”); //Searches forViews/Home/OtherPage.cshtml
}
View – Passing Data from Controller to View
1.ViewBag
• Passing tiny bit of data
• Has some limitations
• LoosingVS IntelliSense
2.StronglyTyped Data
• Passing data objects
• No limitation
• VS IntelliSense works perfectly
View – Passing Data Mechanism
• ViewDataDictionary
• A specialized dictionary class to hold different types of data
• ViewData
• An instance ofViewDataDictionary to read/write data to the
dictionary
• ViewBag (More common)
• A dynamic wrapper forViewData
• ViewBag.Message ≈ViewData[“Message”]
• ViewBag.Message = “Hello MVC”;
• ViewData[“Message”] = “Hello MVC”;
View –ViewBag
• Set (Write) – in Controller
• ViewBag.Message = “Hello MVC”;
• ViewBag.CurrentTime = DateTime.Now;
• Any data type is accepted!
• Get (Read) – inView
• @ViewBag.Message
• @ViewBag.CurrentTime
• IntelliSense doesn’t help you!
View –ViewBag Limitations
• In Controller:
• List<Book> books = new List<Book>();
• Adding some book objects to books
• ViewBag.Books = books;
• returnView();
• InView
• @Foreach (Book b in (ViewBag.Books as IEnumerable<Book>)) (1) OR
• @Foreach (dynamic b inViewBag.Books)
• b. … (2)
• (1): We should cast Dynamic data type before to loop in items!
• (2): IntelliSense doesn’t offer any suggestions!
View – StronglyTypedViews
• In Controller:
• List<Book> books = new List<Book>();
• Adding some book objects to books
• returnView(books);
• InView
• @using MvcApplication1.Models
• @model IEnumrable<Book>
• @Foreach (Book b in Model)
• Remember: Only one type of data can be passed to the view!
View –View Models Need
• Some times we need to transfer multiple types of data toView
• In Controller:
public ActionResult Edit(int id = 0)
{
Book book = db.Books.Find(id);
if (book == null)
{
return HttpNotFound();
}
ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", book.CategoryId);
returnView(book);
}
View –View Models
• Creating additional complicated models for some views
• In Models:
public class ShoppingCartViewModel
{
public IEnumerable<Product> Products { get; set; }
public decimal CartTotal { get; set; }
public string Message { get; set; }
}
• InView:
• @model ShoppingCartViewModel
View – Adding aView
• Adding a newView:
• Create an Action in a Controller
• Right click on the Action name
• AddView
• SelectView Name
• Select Scaffolding Template
• Model class
• Data context class (Entity Framework)
• Reference Script Libraries (required jQuery libraries for validations)
• Create as a Partial View (a view without any master page / layout)
• Use a Layout Page (select a layout page, Default: _layout.cshtml)
View – ScaffoldingTemplates
• Generates a view based on the selected model type
• Scaffolding Templates:
• Empty
• List
• Create
• Details
• Edit
• Delete
• Empty (without model)
View – RazorView Engine
• One of the most requested suggestions received by MVC
Team
• Effectively minimizes the amount of syntax and extra
characters
• Razor sign is @
• Switches from HTML to C#
• Previously was WebFormsView Engine <% … %>
• Don’t overthink it, It JustWorks!!!
View – RazorView Engine Reference
• Code Blocks:
@{
int x = 10;
string name = “Mike”;
}
•Expression:
<span>@model.Message</span>
View – RazorView Engine Reference
•Combining Code & Markup:
@foreach(var item in items) {
<span>@item.Prop</span>
}
•Combining Code & PlainText:
@if (foo) {
<text>PlainText</text>
}
View – RazorView Engine Reference
•Combining Code & Plain Text (alternate):
@if (foo) {
@:PlainText is @bar
}
•Using Blocks:
@ using (Html.BeginForm()) {
<input type="text" value="input here">
}
View – RazorView Engine Reference
•Email Address:
My email address is hossein.aspx@gmail.com
•Server Side Comment:
@*
This is a server side
multiline comment
*@
View – RazorView Engine Reference
•Calling a Generic Method:
@(MyClass.MyMethod<AType>())
•Url Resolution withTilde:
<script src=“~/content/jquery.js”></script>
• At Sign:
• If you need at sign itself Use @@ instead
• ATwitter handle: follow me @@Hossein.aspx
• @section & @RenderSection
View –ViewStart
•_ViewStart.cshtml
• Applies the default Layout page for all views
• Removes the redundancy
@{
Layout = "∼/Views/Shared/_Layout.cshtml";
}
View – Specifying a PartialView
•An stand alone full view
•No _layout.cshtml
•Specified in the Controller:
public ActionResult Message() {
ViewBag.Message = "This is a partial view.";
return PartialView();
}
View – HTML Encoding
• Potential Cross-Site Scripting Injections (XSS)
• Razor automatically Encodes all Html Outputs
• InView:
@{
string message = "<script>alert('hacked!');</script>";
}
<span>@message</span>
• Show in Browser’s Source Code Page:
<span><script>alert(&#39;hacked!&#39;);</script></span>
Model
Model – Basics
•Models contain all application core (Business
Logic,Validation Login, Data Access Login)
•Models are C# classes
•Models hold and manipulate application data
•Models are placed in the Models folder
•Models define relationships between classes
•Models map C# classes to database tables
Model – Conventions
•Model classes doesn’t have any constructor
•Model classes and their properties must be public
•public int Id generates P.K and Identity in
database
•Virtual accessor for properties is used to define
relations between classes
•1:1 , 1:n , n:n relations can be defined in models
Model – Data Annotations
• DataType: Specify the datatype of a property
• DisplayName: Specify the display name for a property.
• DisplayFormat: Specify the display format for a property like different format for Date
proerty.
• Required: Specify a property as required.
• ReqularExpression: Validate the value of a property by specified regular expression
pattern.
• Range:Validate the value of a property with in a specified range of values.
• StringLength: Specify min and max length for a string property.
• MaxLength: Specify max length for a string property.
• ScaffoldColumn: Specify fields for hiding from editor forms.
• Bind: Specify fields to include or exclude when adding parameter or form values to model
properties. (Class specific data annotation)
Model – Code First vs Database First
Model – Code First (Model First)
• The Code First approach allows us to define the model from the code
without generating classes that are generally coupled with the
framework.
• In code first, model objects are defined with POCOs , "Plain Old CLR
Objects". POCOs are simple plain classes that have no inheritance and do
not implement interfaces. We can automatically generate the database
from them, or we can use an existing database and generate the class
mapping from the code.
• The benefits of using this approach is that the Model remains
independent from the persistence framework (in this case, Entity
Framework), as the POCOs classes are not coupled with the mapping
framework.
Model – Code First Implimentation
• 1. Create a Database in MSSQL Server (Version Independent)
• 2. Configuring "DefaultConnection" ConnectionString in Web.Config
• 3. Nuget Package Manager Console: enable-migrations
• 4. DbSet in IndentityModel.cs => ApplicationDbContext
• 5. Nuget Package Manager Console: add-migration InitialCreate
• 6. Nuget Package Manager Console: update-database -targetmigration
InitialCreate
• 7. Seed Method => Adding objects
• 8. Follow the Step 6 again
Model – Scaffolding
• The term "Scaffolding" is used by many software
technologies to mean "quickly generating a basic outline
of your software that you can then edit and customize".
• ASP.NET Scaffolding is a code generation framework for
ASP.NET Web applications.Visual Studio 2013 includes
pre-installed code generators for MVC andWeb API
projects.You add scaffolding to your project when you
want to quickly add code that interacts with data models.
Using scaffolding can reduce the amount of time to
develop standard data operations in your project.
Model –What is Scaffolding?
• The term "Scaffolding" is used by many software
technologies to mean "quickly generating a basic outline
of your software that you can then edit and customize".
• ASP.NET Scaffolding is a code generation framework for
ASP.NET Web applications.Visual Studio 2013 includes
pre-installed code generators for MVC andWeb API
projects.You add scaffolding to your project when you
want to quickly add code that interacts with data models.
Using scaffolding can reduce the amount of time to
develop standard data operations in your project.
Model – Scaffolding – Step 1
Model – Scaffolding – Step 1
Model – Scaffolding – Step 3
Model – Scaffolding – Step 4
Bootstrap
Bootstrap –What is Bootstrap?
• Bootstrap is the most popular HTML,CSS, and JavaScript framework for developing
responsive, mobile-first web sites.
• Bootstrap is completely free to download and use!
• Bootstrap is a free and open-source collection of tools for creating websites and web
applications. It contains HTML- and CSS-based design templates for typography, forms,
buttons, navigation and other interface components, as well as optional JavaScript
extensions.The bootstrap framework aims to ease web development.
• Bootstrap is a front end, that is an interface between the user and the server-side code
which resides on the "back end" or server. And it is a web application framework, that is a
software framework which is designed to support the development of dynamic websites
and web applications.
• As of March 2015, it was the most-starred project on GitHub, with over 78,000 stars and
more than 30,000 forks.
Bootstrap –Why use Bootstrap?
•Easy to use: Anybody with just basic knowledge of
HTML and CSS can start using Bootstrap
•Responsive features: Bootstrap's responsive CSS
adjusts to phones, tablets, and desktops
•Mobile-first approach: In Bootstrap 3, mobile-first
styles are part of the core framework
•Browser compatibility: Bootstrap is compatible with
all modern browsers (Chrome, Firefox, Internet
Explorer, Safari, and Opera)
Bootstrap –Where to get Bootstrap?
•Download Bootstrap from getbootstrap.com
•Include Bootstrap from a CDN bootstrapcdn.com
•Nuget Package Console:
PM> Install-PackageTwitter.Bootstrap.MVC
Bootstrap –Where to get Bootstrap?
•Download Bootstrap from getbootstrap.com
•Include Bootstrap from a CDN bootstrapcdn.com
•Nuget Package Console:
PM> Install-PackageTwitter.Bootstrap.MVC
Bootstrap – Creating the first page – Step 1
•1. Add the HTML5 doctype: Bootstrap uses HTML
elements and CSS properties that require the
HTML5 doctype.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
</html>
Bootstrap – Creating the first page – Step 2
•2. Bootstrap 3 is mobile-first: Bootstrap 3 is designed
to be responsive to mobile devices. Mobile-first styles
are part of the core framework.
<meta name="viewport" content="width=device-width, initial-scale=1">
•The width=device-width part sets the width of the
page to follow the screen-width of the device (which
will vary depending on the device).
•The initial-scale=1 part sets the initial zoom level when
the page is first loaded by the browser.
Bootstrap – Creating the first page – Step 3
•3. Containers: Bootstrap also requires a
containing element to wrap site contents.There
are two container classes to choose from:
•The .container class provides a responsive fixed
width container
•The .container-fluid class provides a full width
container, spanning the entire width of the
viewport
Bootstrap – Creating the first page – Sample
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>My First Bootstrap Page</h1>
<p>This is some text.</p>
</div>
</body>
</html>
Bootstrap – Components
Grid System Button Dropdowns Tooltip
Typography Button Groups Tabs/Pills Popover
Tables Progress Bars Navbar
Images Pagination Froms
Jumbotron Pager Inputs
Wells List Groups Carousel
Glyphicons Panels Modal
Forms
Forms – Using Forms
• The form tag is powerful. Without the form tag, the Internet would be a read-only
repository of boring documentation.You wouldn't be able to search the web or buy
anything (even this book) over the Internet. If an evil genius stole all the form tags from
every website tonight, civilization would crumble by lunchtime tomorrow.
• A form is a container for input elements: buttons, checkboxes, text inputs, and more.
• The two most important attributes of a form tag are the action and the method
attributes.
• Many developers coming to the MVC framework have been using ASP.NET Web
Forms. Web Forms don't expose the full power of the form tag (you could sayWeb
Forms manage and exploit the form tag for their own purposes). It's easy to excuse the
Web Forms developer who forgets what the form tag is capable of—such as creating an
HTTP GET request.
Forms – Action
• The action attribute tells a web browser where to send the
information, so naturally the action contains a URL.The URL can
be relative, or in cases where you want to send information to a
different application or a different server, the action URL can also
be an absolute URL.
• The following form tag sends a search term (the input named q)
to the Bing search page from any application:
<form action="http://www.bing.com/search">
<input name="q" type="text" />
<input type="submit" value="Search!" />
</form>
Forms – Method (GET or POST)
• The form tag in the preceding code snippet does not include a method
attribute.The method attribute tells the browser whether to use an HTTP
POST or HTTP GET when sending the information.You might think the
default method for a form is HTTP POST. After all, you regularly POST
forms to update your profile, submit a credit card purchase, and leave
comments on the funny animal videos onYouTube. However, the default
method value is GET, so by default a form sends an HTTP GET request:
<form action="http://www.bing.com/search" method="get">
<input name="q" type="text" />
<input type="submit" value="Search!" />
</form>
Result: http://www.bing.com/search?q=love
Forms –To GET or to POST?
• Web applications generally use GET requests for reads and POST requests
for writes (which typically include updates, creates, and deletes).
• A request to pay for music uses POST.
• A request to search for music, a scenario you look at next, uses GET.
• In a GET request, the browser puts all the input values into a query string.
• In a POST request, the browser places all the input values inside the body of
the HTTP request.
Forms – Html Helper for From
@using (Html.BeginForm("Search", "Home", FormMethod.Get)) {
<input type="text" name="q" />
<input type="submit" value="Search" />
}
• The BeginForm HTML helper asks the routing engine how to reach the
Search action of the HomeController. Behind the scenes it uses the method
named GetVirtualPath on the Routes property exposed by RouteTable -
that's where your web application registered all its routes in global.asax.
HTML Helpers – Introduction
• HTML helpers are methods you can invoke on the Html property of a view.
You also have access to URL helpers (via the Url property), and Ajax helpers
(via the Ajax property). All these helpers have the same goal, to make views
easy to author.The URL helper is also available from within the controller.
• Most of the helpers, particularly the HTML helpers, output HTML markup.
For example, the BeginForm helper you saw earlier is a helper you can use
to build a robust form tag for your search form.
• Note the BeginForm helper outputs both the opening <form> and the
closing </form>.The helper emits the opening tag during the call to
BeginForm, and the call returns an object implementing IDisposable.
HTML Helpers – More Control
• While protecting you, helpers can also give you the level of control you
need. As an example of what you can achieve with helpers, look at
another overloaded version of the BeginForm helper:
@using (Html.BeginForm("Search", "Home", FormMethod.Get,
new { target = "_blank", @class="editForm", data_validatable=true }))
Result:
<form action="/Home/Search" class="editForm"
data-validatable="true" method="get" target="_blank">
HTML Helpers – Common Helpers
Helper HTML Element
Html.CheckBox <input type="checkbox" />
Html.DropDownList <select></select>
Html.Hidden <input type="hidden" />
Html.Label <label for="" />
Html.ListBox <select></select> or <select multiple></select>
Html.Password <input type="password" />
Html.RadioButton <input type="radio" />
Html.TextArea <textarea></textarea>
Html.TextBox <input type="text" />
Html.ValidationMessage <span></span>
HTML Helpers – StronglyTyped Helpers
Helper HTML Element
Html.CheckBoxFor <input type="checkbox" />
Html.DropDownListFor <select></select>
Html.HiddenFor <input type="hidden" />
Html.LabelFor <label for="" />
Html.ListBoxFor <select></select> or <select multiple></select>
Html.PasswordFor <input type="password" />
Html.RadioButtonFor <input type="radio" />
Html.TextAreaFor <textarea></textarea>
Html.TextBoxFor <input type="text" />
Html.ValidationMessageFor <span></span>
HTML Helpers - Model State
• All the helpers you use to display form values also interact with ModelState. Remember,
ModelState is a byproduct of model binding and holds all validation errors detected during
model binding. Model state also holds the raw values the user submits to update a model.
• Helpers used to render form fields automatically look up their current value in the
ModelState dictionary.The helpers use the name expression as a key into the ModelState
dictionary. If an attempted value exists in ModelState, the helper uses the value from
ModelState instead of a value in view data.
• The ModelState lookup allows bad values to preserve themselves after model binding fails.
For example, if the user enters the value abc into the editor for a DateTime property, model
binding will fail and the value abc will go into model state for the associated property.When
you re-render the view for the user to fix validation errors, the value abc will still appear in
the DateTime editor, allowing the users to see the text they tried as a problem and allowing
them to correct the error.
• When ModelState contains an error for a given property, the form helper associated with
the error renders a CSS class of input-validation-error in addition to any explicitly specified
CSS classes.The default style sheet, style.css, included in the project template contains
styling for this class.
URL Helpers
• The URL helpers are similar to the HTML ActionLink and RouteLink helpers, but instead of
returning HTML they build URLs and return the URLs as strings.There are three helpers:
• Action
• Content
• RouteUrl
• The Action URL helper is exactly like ActionLink, but does not return an anchor tag. For
example, the following code displays the URL (not a link) to browse all book categories in
the store:
<span>
@Url.Action("Browse", "Store", new { category= "ASP.NET" }, null)
</span>
• The result is the following HTML:
<span>
/Store/Browse?category=asp.net
</span>
URL Helpers
• The RouteUrl helper follows the same pattern as the Action helper, but like RouteLink it
accepts a route name and does not have arguments for controller name and action name.
The Content helper is particularly helpful because it can convert a relative application path
to an absolute application path.You'll see the Content helper at work in the Book Store's
_Layout view.
<script src="@Url.Content("∼/Scripts/jquery-1.10.2.min.js")“ type="text/javascript"></script>
• Using a tilde (~) as the first character in the parameter you pass to the Content helper lets
the helper generate the proper URL no matter where your application is deployed (think of
the tilde as representing the application root directory).Without the tilde, the URL could
break if you moved the application up or down the virtual directory tree.
• InASP.NET MVC 5, which uses Razor version 3, the tilde character is resolved automatically
when it appears in the src attribute for script, style, and img elements.The code in the
previous example could also be written as follows and work just fine:
<script src="∼/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
Ajax
Ajax – Introduction to jQuery?
• The jQuery “write less, do more” tagline is a perfect description
of the jQuery experience.
• The API is terse yet powerful.The library itself is flexible yet
lightweight.
• Best of all, jQuery supports all the modern browsers (including
Internet Explorer, Firefox, Safari, Opera, and Chrome), and hides
the inconsistencies (and bugs) you might experience if you wrote
code directly against the API each browser provides.
• jQuery is one of the most popular JavaScript libraries in
existence, and remains an open source project.
• www.jquery.com
Ajax – jQuery Features
•jQuery excels at finding, traversing, and
manipulating HTML elements inside an HTML
document.
•After you've found an element, jQuery also makes
it easy to wire up event handlers on the element,
animate the element, and build Ajax interactions
around the element
Ajax – jQuery Selectors
•Selectors are the strings you pass to the jQuery
function to select elements in the DOM.
Selector Description
$("#header") Find the element with an id of “header"
$(".editor-label") Find all elements with a class name of “.editor-label"
$("div") Find all <div> elements
$("#header div")
Find all <div> elements that are descendants of the element with an id
of “header"
$("#header > div")
Find all <div> elements that are children of the element with an id of
“header"
$("a:even") Find evenly numbered anchor tags
Ajax – jQuery Example 1
$(function () {
$("#album-list img").mouseover(function () {
$(this).animate({ height: "+=25', width: "+=25" })
.animate({ height: "-=25', width: "-=25" });
});
});
Ajax – jQuery Example 2
$("a").mouseover(function () {
$(this).addClass("highlight");
}).mouseout(function () {
$(this).removeClass("highlight");
});
Ajax – jQuery Shortcuts
•All the jQuery methods you use against a wrapped set,
like the mouseover method, return the same jQuery
wrapped set.This means you can continue invoking
jQuery methods on elements you've selected without
reselecting those elements.We call this method chaining.
•Shortcuts are available in jQuery for many common
operations. Setting up effects for mouseover and
mouseout is a common operation, and so is toggling the
presence of a style class.
Ajax – jQuery Example 3
$("a").hover(function () {
$(this).toggleClass("highlight");
});
Ajax & jQuery
• jQuery includes everything you need to send asynchronous
requests back to your webserver.You can generate POST
requests or GET requests and jQuery notifies you when the
request is complete (or if there is an error).With jQuery, you
can send and receive XML data (the x in Ajax stands for XML,
after all), but as you'll see in this chapter, consuming data in
HTML, text, or JavaScript Object Notation (JSON) format is
trivial. jQuery makes Ajax really easy.
• In fact, jQuery makes so many things easy it has changed the
way web developers write script code.
Ajax – Unobtrusive JavaScript
• Unobtrusive JavaScript is the practice of keeping JavaScript
code separate from markup.You package all the script code
you need into .js files. If you look at the source code for a
view, you don't see any JavaScript intruding into the markup.
Even when you look at the HTML rendered by a view, you
still don't see any JavaScript inside.The only sign of script
you'll see is one or more <script> tags referencing the
JavaScript files.
• Old way sample:
<div onclick="javascript:alert('click');">Testing, testing</div>
Ajax – MVC & jQuery
•jQuery is in MVC projects by default
•jQuery can be downloaded from Nuget
•jQuery is being bundled in BundleConfig.cs
•@section Scripts
•List of default JavaScript files in the Script folder
Ajax Helpers
• The Ajax functionality of the Ajax helpers will not work
without a reference to the jquery.unobtrusive-ajax.js script.
If you're having trouble with the Ajax helpers, this is the first
thing you should check.
• Adding the Unobtrusive Ajax Script toYour Project:
• Microsoft jQuery Unobtrusive Ajax Nuget Package
• Install- Package Microsoft.jQuery.Unobtrusive.Ajax
• Adding <script src="~/Scripts/jquery.unobtrusive-
ajax.min.js"> </script> after jQuery
Ajax Helpers - @Ajax.ActionLink
<div id="dailydeal">
@Ajax.ActionLink("View Deals",
"DailyDeal",
null,
new AjaxOptions
{
UpdateTargetId = "dailydeal",
InsertionMode =
InsertionMode.Replace,
HttpMethod = "GET"
},
new {@class = "btn btn-primary"})
</div>
Controller:
public ActionResult DailyDeal()
{
var album = GetDailyDeal();
return PartialView("_DailyDeal", album);
}
Ajax Helpers – Rendered Markup
<div id="dailydeal">
<a class="btn btn-primary" data-ajax="true" data-ajax-
method="GET " data-ajax-mode="replace" data-ajax-
update="#dailydeal" href="/Home/DailyDeal">
View Deals
</a>
</div>
Ajax Helpers – @Ajax.Form
@using (Ajax.BeginForm(“BookSearch", "Home",
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnFailure = "searchFailed",
LoadingElementId = "ajax-loader",
UpdateTargetId = "searchresults",
}))
{
<input type="text" name="q" />
<input type="submit" value="search" />
<img id="ajax-loader" src="@Url.Content("~/Images/ajax-loader.gif") " style="display:none" />
}
<div id="searchresults"></div>
Ajax Helpers – @Ajax.Form
Controller:
public ActionResult ArtistSearch(string q)
{
var artists = GetArtists(q);
return PartialView(artists);
}
Failure JavaScript:
function searchFailed() {
$("#searchresults").html("Sorry, there was a problem with the search.");
}
Ajax Helpers – @Ajax.Form
View:
@model IEnumerable<MvcMusicStore.Models.Artist>
<div id="searchresults">
<ul>
@foreach (var item in Model) {
<li>@item.Name</li>
}
</ul>
</div>
Ajax – jQueryValidations
• By default, unobtrusive JavaScript and client-side validation are enabled in an ASP.NET
MVC application. However, you can change the behavior through web.config settings.
If you open the root-level web.config file in a new application, you'll see the following
appSettings configuration section:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
• If you want to turn off either feature throughout the application, you can change either
setting to false. In addition, you can also control these settings on a view-by view
basis.The HTML helpers EnableClientValidation and EnableUnobtrusiveJavascript
override the configuration settings inside a specific view.
• The primary reason to disable either feature is to maintain backward compatibilitywith
custom scripts.
Security,
Authentication and
Authorization
Security – Web Form Features
• Server Components automatically HTML encode displayed
values and attributes to help prevent XSS attacks.
• ViewState is encrypted and validated to help prevent
tampering with form posts.
• RequestValidation (<% @page validaterequest="true" %>)
intercepts maliciouslookingdata and offers a warning (this is
still turned on by default with ASP.NET MVC).
• EventValidation helps prevent injection attacks and posting
of invalid values.
Security – MVC Way
• ASP.NET MVC gives you more control over markup and how your
application functions, which means you've taken on more
responsibility.
• To be clear, ASP.NET MVC does offer you a lot of built-in protection
(for example, features like HTML encoding by default use HTML
helpers and Razor syntax, request validation, and use scaffolded
controllers whitelist form elements to prevent over-posting
attacks).
• However, you can easily shoot yourself in the foot if you don't
understand web
• Never, ever trust any data your users give you!
Security – Some Practical Examples (1)
• Any time you render data that originated as user input, encode it.
The most common practice is to HTML encode it, though you
sometimes need to HTML attribute encode it if it's displayed as an
attribute value, or JavaScript encode it if it's being used in a
JavaScript code snippet. And sometimes you need multiple layers
of encoding, such as a JavaScript code snippet in an HTML page.
• Think about what portions of your site should be available for
anonymous access, and require authentication on the others.
• Don't try to sanitize your users' HTML input yourself (using regular
expressions or some other method)—you'll lose.
Security – Some Practical Examples (2)
• Use HTTP-only cookies when you don't need to access
cookies via client-side script (which is most of the time).
• Remember that external input isn't just obvious form fields;
it includes URL query string values, hidden form fields, Ajax
requests, results of external web services you're using, and
more.
• Consider using the AntiXSS encoder (a component of the
MicrosoftWeb Protection Library, which is now distributed
with ASP.NET 4.5 and higher).
Security – Conclusion
You have users and enemies, and they are waiting for you
to build this application of yours so they can come and
break into it. Hackers, crackers, spammers, viruses,
malware, they all want access to your application and the
files on it. If you haven't faced this before, it's usually for
one of two reasons:
•You haven't built an application yet.
•You didn't find out that someone hacked your
application.
Authentication & Authorization
Sometimes people get confused with respect to the difference
between user authentication and user authorization. Getting
these concepts confused is easy to do, but in summary:
• Authentication is verifying that users are who they say they
are, using some form of login mechanism
(username/password, OpenID, OAuth and so on—something
that says “this is who I am”).
• Authorization is verifying that they can do what they want
to do with respect to your site.This is usually achieved using
some type of role-based or claim-based system.
Authorize Attribute
• The first, simplest step in securing an application is requiring
that a user be logged in to access specific parts of the
application.You can do that using the Authorize action filter
on a controller, on specific actions within a controller, or even
globally for the entire application.
• The AuthorizeAttribute is the default authorization filter
included with ASP.NET MVC. Use it to restrict access to an
action method. Applying this attribute to a controller is
shorthand for applying it to every action method within the
controller.
Authorize Attribute – Best Practice
A good approach to security is to always put the security check as close as
possible to the thing you are securing.You might have other checks higher
up the stack, but ultimately, you want to secure the actual resource.This
way, no matter how the user got to the resource, there will always be a
security check. In this case, you don't want to rely on routing and URL
authorization to secure a controller; you really want to secure the controller
itself.The AuthorizeAttribute serves this purpose.
• If you don't specify any roles or users, the current user must simply be
authenticated in order to call the action method.This is an easy way to
block unauthenticated users from a particular controller action.
• If a user attempts to access an action method with this attribute applied
and fails the authorization check, the filter causes the server to return a
“401 Unauthorized” HTTP status code.
Securing Controller Actions
[Authorize]
publicActionResult Buy(int id)
{
var album = GetAlbums().Single(a => a.AlbumId == id);
returnView(album);
}
Using URL Authorization
• A common means of securing an application withWeb
Forms is to use URL authorization. For example, if you have
an admin section and you want to restrict it to users who are
in the Admins role, you might place all your admin pages in
an admin folder and deny access to everyone except those in
the Admins role to that subfolder.
• With ASP.NETWeb Forms, you can secure a directory on
your site by locking it down in the web.config.
• If you want to keep secure all the files in a directory, you
should secure the whole directory with Web Forms!
Using URL Authorization – Web.Config
<location path= "Admin" allowOverride="false">
<system.web>
<authorization>
<allow roles= "Administrator" />
<deny users="?" />
</authorization>
</system.web>
</location>
With MVC this approach won't work so well for two reasons:
• Requests no longer map to physical directories.
• There may be more than one way to route to the same controller.
Account Controller
It's nice that the AccountController - and its associated views - are all provided in the
ASP.NET MVC with the individual user accounts authentication template.
In simple cases, adding authorization doesn't require any additional code or
configuration. Equally nice, though, is that you can change any of those parts:
• The AccountController (as well as the associatedAccount models and views) is a
standard ASP.NET MVC controller, which is pretty easy to modify.
• The authorization calls work against standard OWIN middleware components
published in the ASP.NET Identity system.You can switch authentication
middleware components or write your own.
• The AuthorizeAttribute is a standard authorization attribute, implementing
IAuthorizeFilter.You can create your own authorization filters.
Securing Entire Controllers
• The earlier scenario demonstrated a single controller with the
AuthorizeAttribute applied to specific controller actions.
• You may want to secure an entire Contoller. In this case you can put the
AuthorizeAttribute on the Contoller.
[Authorize]
public class CheckoutController : Controller
Securing Entire Application using a Global Authorization Filter
• For many sites, nearly the entire application should require authorization. In
this case, requiring authorization by default and making exceptions in the
few places where anonymous access is allowed—such as the site's home
page and URLs required for the login process—is simpler.
• For this case, configuring the AuthorizeAttribute as a Global Filter and
allowing anonymous access to specific controllers or methods using the
AllowAnonymous attribute is a good idea.
• Global Authorization Is Global Only to MVC. Keep in mind that a global
filter applies only to MVC controller actions. It doesn't secure Web Forms,
static content, or other ASP.NET handlers.
Global Authorization Filter
• To register the AuthorizeAttribute as a global filter, add it to the global filters
collection in the RegisterGlobalFilters method, located in
App_StartFilterConfig.cs:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
filters.Add(new HandleErrorAttribute());
}
• This applies the AuthorizeAttribute to all controller actions in the application.
• To allow an exception for a Controller or Action you can put [AllowAnonymous]
Specify Roles & Users with AuthorizeAttribute
If you need the ability to limit access to specific roles or users. Fortunately,
AuthorizeAttribute allows you to specify both roles and users, as shown here:
[Authorize(Roles="Administrator")]
public class StoreManagerController : Controller
[Authorize(Roles="Administrator,SuperAdmin")]
public class TopSecretController:Controller
[Authorize(Users="Jon,Phil,Scott,Brad,David")]
public class TopSecretController:Controller
[Authorize(Roles="SuperAdmin", Users="Jon,Phil,Brad,David")]
public class TopSecretController:Controller
Managing users and roles in User Identity
One of the design requirements forASP.NET Identity is to allow for extensive
customization without undue pain. Some of the extensibility points include:
1. Adding additional user profile data is now trivial.
2. Persistence control is supported through the use of UserStore and
RoleStore abstractions over the data access layer.
3. The RoleManager makes it easy to create roles and manage role
membership.
1. Storing Additional User Profile Data
It's a very common requirement to store additional information about your users:
birthday,Twitter handle, site preferences, etc. In the past, adding additional profile
data was unnecessarily difficult. In ASP.NET Identity, users are modeled using an
Entity Framework Code First model, so adding additional information to your users is
as simple as adding properties to your ApplicationUser class (found in
/Models/IdentityModels.cs). For example, to add an Address andTwitter handle to
your user, youd just add the following properties:
public class ApplicationUser : IdentityUser
{
public string Address { get; set; }
public stringTwitterHandle { get; set; }
}
More Details: http://go.microsoft.com/fwlink/?LinkID=317594
2. Persistence Control
• By default, ASP.NET Identity implements data storage using Entity
Framework Code First, so you can customize the data storage in any way
you'd normally configure Entity Framework (e.g. pointing the connection
string at any database Entity Framework supports.)
• Additionally, ASP.NET Identity's data storage is built on top of the
UserStore and RoleStore abstractions.You can implement your own
UserStore and / or RoleStore to persist your data in any way you'd like,
including AzureTable Storage, custom file formats, web service calls, etc.
• This tutorial explains the concepts in detail, with a link to an example using
MySQL: http://www.asp.net/identity/overview/extensibility/overview-of-
custom-storageproviders-for-aspnet-identity
3. Persistence Control
• ASP.NET Identity includes a UserManager and RoleManager which make it
easy to perform common tasks like creating users and roles, adding users to
roles, checking if a user is in a role, etc.
• A detailed example is available here: http://azure.microsoft.com/enus/
documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-app-
membership-oauthsql-database/
• It's great that you've got these extensibility points when you need them. For
the most part, if you're using the standard AccountController and storing
user information via Entity Framework, you just code away without
considering the extensibility points—until you want them.
EXTERNAL LOGINVIA OAUTH AND OPENID
• Historically, the huge majority of web applications have handled authorization based on a
locally maintained account database.
• Although traditional membership is a great fit in a lot of web applications, it comes with
some serious downsides:
• Maintaining a local database of usernames and secret passwords is a large security
liability. Large security breaches involving hundreds of thousands of users‘ account
information (often including unencrypted passwords) have become common.Worse,
because many users reuse passwords on multiple websites, compromised accounts may
affect your users' security on their banking or other sensitive websites.
• Website registration is annoying. Users have gotten tired of filling out forms, complying
with widely differing password policies, remembering passwords, and worrying whether
your site is going to keep their information secure. A significant percentage of potential
users will decide they would rather not bother with registering for your site.
• Technically, the OAuth protocol was designed for authorization, but in general use it's
frequently used for authentication.
Trusted External Login Providers
Supporting only providers whose security you trust, which generally means
sticking with well-known providers, is important for a couple reasons:
• When you are redirecting your users to external sites, you want to make sure that
these sites are not malicious or poorly secured ones that will leak or misuse your
users' login data or other information.
• Authentication providers are giving you information about users—not just their
registration state, but also e-mail addresses and potentially other provider-specific
information. Although by default this additional information isn't stored, reading
provider data such as e-mail to prevent the user from having to re-enter it is not
uncommon. A provider could potentially—either accidentally or maliciously—
return information. Displaying any provider information to the user before you
store it is generally a good idea.
Requiring SSL for Login
• The callback from an external provider to your site contains security tokens that allow access to your
site and contain user information.Transmitting this information over HTTPS to prevent interception
while this information travels over the Internet is important.
• To enforce HTTPS for this callback, applications that support external logins should require HTTPS for
access to the AccountController's Login GET method using the
[RequireHttps]
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
• Enforcing HTTPS during login to your site causes all calls to external providers to occur over HTTPS, which,
in turn, causes the providers to make their callbacks to your site using HTTPS.
• Additionally, using HTTPS with Google authentication is important. Google reports a user who logs in once
via HTTP and later via HTTPS as two different people. Always requiring HTTPS prevents this problem.
Routing
Understanding URLs
Some guidelines for high-quality URLs:
• Choosing a domain that is easy to remember and easy to spell
• Short URLs
• Easy to type URLs
• URLs that reflect site structure
• URLs that are hackable to allow users to move to higher levels of the
information architecture by hacking off the end of the URL
• Persistent URLs, which don't change
MVC vs. Web Forms
• InWeb Forms a direct relationship exists between the URL and what
physically exists on disk. A request for this URL is received by the web
server, which executes some code associated with this file to produce a
response.
• MVC generally takes a different approach by mapping the URL to a method
call on a class, rather than some physical file.These classes are generally
called controllers because their purpose is to control the interaction
between the user input and other components of the system.The methods
that serve up the response are generally called actions.These represent the
various actions the controller can process in response to user input requests.
URL vs. URI
URL: Uniform Resource Locator
URI: Uniform Resource Identifier
• All URLs are technically URIs.TheW3C has said, at
www.w3.org/TR/uriclarification/# contemporary, that a “URL is a useful but
informal concept:A URL is a type of URI that identifies a resource via a
representation of its primary access mechanism.”
• In other words, a URI just identifies a resource, but a URL also tells you how to
get it.
Introduction to Routing
Routing within the ASP.NET MVC framework serves two main
purposes:
• It matches incoming requests that would not otherwise match a file on the
file system and it maps the requests to a controller action.
• It constructs outgoing URLs that correspond to controller actions.
Comparing Routing to URL Rewriting
• The key difference is that URL rewriting is focused on mapping one URL to
another URL.
• For example, URL rewriting is often used for mapping old sets of URLs to a
new set of URLs. Contrast that to Routing, which is focused on mapping a
URL to a resource. It constructs outgoing URLs that correspond to controller
actions.
• Another key difference is that Routing also helps generate URLs using the
same mapping rules that it uses to match incoming URLs. URL rewriting
applies only to incoming requests and does not help in generating the
original URL.
Routing Approaches
• MVC has always supported a centralized, imperative, code-based style of
defining routes that we'll call traditional routing.This is a good option that
is still fully supported.
• MVC 5 adds a second option using declarative attributes on your controller
classes and action methods, which is called attribute routing.This new
option is simpler.
• Both options work well, and both are flexible enough to handle complex
routing scenarios.Which option to choose is largely a matter of style and
preference.
Defining Attribute Routes
• Every ASP.NET MVC application needs routes to allow it to handle requests.
• Routes are the entry points into your MVC application.
• A route definition starts with a URL template, which specifies the pattern that the
route will match.
• Route definitions can appear as attributes on either the controller class or on an
action method.
• Routes can also specify constraints and default values for the various parts of the
URL, providing tight control over how and when the route matches incoming
request URLs.
• Routes can even have names associated with them, which comes into play for
outgoing URL construction (the second main purpose of Routing).
Route URLs
• Global.asax.cs  RouteConfig.RegisterRoutes(RouteTable.Routes);
• App_Start  RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
}
• Controllers  HomeController.cs
[Route("about")] // RouteTemplate
public ActionResult About()
Route URLs Examples (1)
• Single RouteTemplate
[Route("about")]
public ActionResult About()
• Multiple RouteTemplate
[Route("about")]
[Route("home/about")]
public ActionResult About()
Route URLs Examples (2)
• RouteValues
[Route("book/{id}")]
public ActionResult Details(int id)
• Multiple RouteValues
[Route("{year}/{month}/{day}")]
public ActionResult Index(string year, string month, string day)
Route URLs Examples (3)
• Controller Routes
[Route("home/{action}")]
public class HomeController : Controller
• Controller Routes + Action Routes
[Route("home/{action}")]
public class HomeController : Controller
{
[Route("home")]
[Route("home/index")]
public ActionResult Index()
Route URLs Examples (4)
• Route Prefix
[RoutePrefix("home")]
[Route("{action}")]
public class HomeController : Controller
{
[Route("")]
[Route("index")]
public ActionResult Index()
Route Constraints
[Route("book/{id:int}")]
public ActionResult Details(int id)
{
returnView();
}
[Route("book/{title}")]
public ActionResult Details(string title)
{
returnView();
}
Route ConstraintsTable
Route Defaults
[Route("home/{action=Index}")]
public class HomeController : Controller
{
public ActionResult Index()
{
returnView();
}
public ActionResult About()
{
returnView();
}
}
Route Optional Parameter
[RoutePrefix("books")]
[Route("{action}/{id?}")]OR [Route("{action=Index}/{id?}")]
public class BooksController : Controller
{
public ActionResult Index()
{
returnView();
}
public ActionResult Details(int id)
{
returnView();
}
DefiningTraditional Routes
• Global.asax.cs  RouteConfig.RegisterRoutes(RouteTable.Routes);
• App_Start  RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("simple", "{first}/{second}/{third}");
}
DefiningTraditional Routes
• RouteValues
routes.MapRoute("simple", "{controller}/{action}/{id}");
• Optional Parameters
routes.MapRoute("simple", "{controller}/{action}/{id}",
new {id = UrlParameter.Optional});
• DefaultValues
routes.MapRoute("simple", "{controller}/{action}/{id}",
new { id = UrlParameter.Optional, action = "index" });
DefiningTraditional Routes
• Route Constraints
routes.MapRoute("blog", "{year}/{month}/{day}",
new { controller = "blog", action = "index" },
new { year = @"d{4}", month = @"d{2}", day = @"d{2}" });
Combining Attribute Routing withTraditional Routing
• Both support route templates, constraints, optional values, and defaults.
• The syntax is a little different, but the functionality they offer is largely equivalent, because
under the hood both use the same Routing system.
• You can use either attribute routing, traditional routing, or both.
• Routing checks each route in order and chooses the first route that matches.
• If there's any overlap between a traditional route and an attribute route, the first route
registered wins.
• It is recommended to put the MapMvcAttributeRoutes call first.
• Attribute routes are usually more specific, and having attribute routes come first allows
them to take precedence over traditional routes, which are usually more generic.
Choosing Attribute Routes orTraditional Routes
Should you use attribute routes or traditional routes? Either option is
reasonable, but here are some suggestions on when to use each one.
Consider choosing traditional routes when:
• You want centralized configuration of all your routes.
• You use custom constraint objects.
• You have an existing working application you don't want to change.
Consider choosing attribute routes when:
• You want to keep your routes together with your action's code.
• You are creating a new application or making significant changes to an existing one.
Catch-All Parameter
• A catch-all parameter allows for a route to match part of a URL with an
arbitrary number of segments.
• The value put in the parameter is the rest of the URL path (that is, it
excludes the query string, if any).
• A catch-all parameter is permitted only as the last segment of the route.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("catchallroute", "query/{query-name}/{*extrastuff}");
}
Catch-All Parameter Requests
URL ParameterValue
/query/select/a/b/c extrastuff = "a/b/c"
/query/select/a/b/c/ extrastuff = "a/b/c/"
/query/select/ extrastuff = null (Route still matches.The catch-all
just catches the null string in this case.)
Multiple Route Parameters in a Segment
A route URL may have multiple parameters per segment. For example, all the
following are valid route URLs:
• {title}-{artist}
• Album{title}and{artist}
• {filename}.{ext}
To avoid ambiguity, parameters cannot be adjacent. For example, the
following are invalid:
• {title}{artist}
• Download{filename}{ext}
Matching Route URLs with Multiple Parameters
Route URL Request URL Route Data Result
{filename}.{ext} /Foo.xml.aspx filename="Foo.xml"ext="aspx"
My{location}-{subloc} /MyHouse-dwelling location="House“ subloc="dwelling"
{foo}xyz{bar} /xyzxyzxyzblah foo="xyzxyz"bar="blah"
StopRoutingHandler and IgnoreRoute
• By default, Routing ignores requests that map to physical files on disk.
That's why requests for files such as CSS, JPG, and JS files are ignored by
Routing and handled in the normal manner.
• However, in some situations, there are requests that don't map to a file on
disk that you don't want Routing to handle. For example, requests for
ASP.NET's web resource handlers, WebResource.axd, are handled by an
HTTP handler and don't correspond to a file on disk.
• One way to ensure that Routing ignores such requests is to use the
StopRoutingHandler.
StopRoutingHandler and IgnoreRoute
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("{resource}.axd/{*pathInfo}",new StopRoutingHandler()));
OR
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
}
Some Useful
Nuget Packages
MVC Nuget Packages
Packages
ELMAH.MVC PagedList.Mvc
Glimpse.MVC5 WebBackgrounder
Modernizr Lucene.NET
Grid.Mvc AnglicanGeek.MarkdownMailer
Bootstrap Helpers Persia

More Related Content

What's hot

What's hot (20)

Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Web forms in ASP.net
Web forms in ASP.netWeb forms in ASP.net
Web forms in ASP.net
 
Tailwind CSS.11.pptx
Tailwind CSS.11.pptxTailwind CSS.11.pptx
Tailwind CSS.11.pptx
 
WEB DEVELOPMENT USING REACT JS
 WEB DEVELOPMENT USING REACT JS WEB DEVELOPMENT USING REACT JS
WEB DEVELOPMENT USING REACT JS
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
ASP.NET Lecture 1
ASP.NET Lecture 1ASP.NET Lecture 1
ASP.NET Lecture 1
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
Mvc
MvcMvc
Mvc
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
React js
React jsReact js
React js
 
Tech talk on Tailwind CSS
Tech talk on Tailwind CSSTech talk on Tailwind CSS
Tech talk on Tailwind CSS
 
Why MVC?
Why MVC?Why MVC?
Why MVC?
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 

Viewers also liked

Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overviewukdpe
 
ASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksRandy Connolly
 
ASP.NET 12 - State Management
ASP.NET 12 - State ManagementASP.NET 12 - State Management
ASP.NET 12 - State ManagementRandy Connolly
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksRandy Connolly
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1Hossein Zahed
 
Microsoft SQL Server 2008
Microsoft SQL Server 2008Microsoft SQL Server 2008
Microsoft SQL Server 2008Hossein Zahed
 
Generic repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkGeneric repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkMd. Mahedee Hasan
 
Ruby on Rails vs. ASP.NET MVC
Ruby on Rails vs. ASP.NET MVCRuby on Rails vs. ASP.NET MVC
Ruby on Rails vs. ASP.NET MVCShay Friedman
 
Manifesto Seminar - Joanna Chataway on Below the Radar Innovation
Manifesto Seminar - Joanna Chataway on Below the Radar InnovationManifesto Seminar - Joanna Chataway on Below the Radar Innovation
Manifesto Seminar - Joanna Chataway on Below the Radar InnovationSTEPS Centre
 
Introducing asp.net web pages 2
Introducing asp.net web pages 2Introducing asp.net web pages 2
Introducing asp.net web pages 2Uh-meet Thapa
 
Sexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroidsSexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroidsDmytro Zaitsev
 
Architecting ASP.NET MVC Applications
Architecting ASP.NET MVC ApplicationsArchitecting ASP.NET MVC Applications
Architecting ASP.NET MVC ApplicationsGunnar Peipman
 
Repository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsRepository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsHatim Hakeel
 

Viewers also liked (20)

Big Data World
Big Data WorldBig Data World
Big Data World
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
 
HTML & XHTML Basics
HTML & XHTML BasicsHTML & XHTML Basics
HTML & XHTML Basics
 
ASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET Works
 
ASP.NET 12 - State Management
ASP.NET 12 - State ManagementASP.NET 12 - State Management
ASP.NET 12 - State Management
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
SEO Fundamentals
SEO FundamentalsSEO Fundamentals
SEO Fundamentals
 
Microsoft SQL Server 2008
Microsoft SQL Server 2008Microsoft SQL Server 2008
Microsoft SQL Server 2008
 
Generic repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkGeneric repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity Framework
 
Ruby on Rails vs. ASP.NET MVC
Ruby on Rails vs. ASP.NET MVCRuby on Rails vs. ASP.NET MVC
Ruby on Rails vs. ASP.NET MVC
 
Manifesto Seminar - Joanna Chataway on Below the Radar Innovation
Manifesto Seminar - Joanna Chataway on Below the Radar InnovationManifesto Seminar - Joanna Chataway on Below the Radar Innovation
Manifesto Seminar - Joanna Chataway on Below the Radar Innovation
 
Introducing asp.net web pages 2
Introducing asp.net web pages 2Introducing asp.net web pages 2
Introducing asp.net web pages 2
 
Innovation Training
 Innovation Training  Innovation Training
Innovation Training
 
Viper architecture
Viper architectureViper architecture
Viper architecture
 
Sexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroidsSexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroids
 
Architecting ASP.NET MVC Applications
Architecting ASP.NET MVC ApplicationsArchitecting ASP.NET MVC Applications
Architecting ASP.NET MVC Applications
 
MVP Clean Architecture
MVP Clean  Architecture MVP Clean  Architecture
MVP Clean Architecture
 
Repository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsRepository and Unit Of Work Design Patterns
Repository and Unit Of Work Design Patterns
 

Similar to ASP.NET MVC 5 - EF 6 - VS2015

Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013Thomas Robbins
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
Asp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantAsp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantNitin Sawant
 
2011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 52011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 5Daniel Fisher
 
Introduction to ASP.Net MVC
Introduction to ASP.Net MVCIntroduction to ASP.Net MVC
Introduction to ASP.Net MVCSagar Kamate
 
ASP.NET MVC 2.0
ASP.NET MVC 2.0ASP.NET MVC 2.0
ASP.NET MVC 2.0Buu Nguyen
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 
Intro to .NET for Government Developers
Intro to .NET for Government DevelopersIntro to .NET for Government Developers
Intro to .NET for Government DevelopersFrank La Vigne
 
Using MVC with Kentico 8
Using MVC with Kentico 8Using MVC with Kentico 8
Using MVC with Kentico 8Thomas Robbins
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introductionBhagath Gopinath
 
MVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming modelMVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming modelAlex Thissen
 
Building RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPIBuilding RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPIGert Drapers
 
MVC 6 - Tag Helpers and View Components
MVC 6 - Tag Helpers and View ComponentsMVC 6 - Tag Helpers and View Components
MVC 6 - Tag Helpers and View ComponentsDavid Paquette
 
Backbone JS for mobile apps
Backbone JS for mobile appsBackbone JS for mobile apps
Backbone JS for mobile appsIvano Malavolta
 
SoCal Code Camp 2011 - ASP.NET 4.5
SoCal Code Camp 2011 - ASP.NET 4.5SoCal Code Camp 2011 - ASP.NET 4.5
SoCal Code Camp 2011 - ASP.NET 4.5Jon Galloway
 
Code igniter overview
Code igniter overviewCode igniter overview
Code igniter overviewumesh patil
 

Similar to ASP.NET MVC 5 - EF 6 - VS2015 (20)

Asp.Net MVC 5 in Arabic
Asp.Net MVC 5 in ArabicAsp.Net MVC 5 in Arabic
Asp.Net MVC 5 in Arabic
 
Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Asp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantAsp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin Sawant
 
2011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 52011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 5
 
Introduction to ASP.Net MVC
Introduction to ASP.Net MVCIntroduction to ASP.Net MVC
Introduction to ASP.Net MVC
 
ASP.NET MVC 2.0
ASP.NET MVC 2.0ASP.NET MVC 2.0
ASP.NET MVC 2.0
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
Intro to .NET for Government Developers
Intro to .NET for Government DevelopersIntro to .NET for Government Developers
Intro to .NET for Government Developers
 
Using MVC with Kentico 8
Using MVC with Kentico 8Using MVC with Kentico 8
Using MVC with Kentico 8
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introduction
 
MVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming modelMVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming model
 
Asp.Net MVC
Asp.Net MVCAsp.Net MVC
Asp.Net MVC
 
ASP.NET MVC 3
ASP.NET MVC 3ASP.NET MVC 3
ASP.NET MVC 3
 
Building RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPIBuilding RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPI
 
MVC 6 - Tag Helpers and View Components
MVC 6 - Tag Helpers and View ComponentsMVC 6 - Tag Helpers and View Components
MVC 6 - Tag Helpers and View Components
 
Backbone JS for mobile apps
Backbone JS for mobile appsBackbone JS for mobile apps
Backbone JS for mobile apps
 
Mvc fundamental
Mvc fundamentalMvc fundamental
Mvc fundamental
 
SoCal Code Camp 2011 - ASP.NET 4.5
SoCal Code Camp 2011 - ASP.NET 4.5SoCal Code Camp 2011 - ASP.NET 4.5
SoCal Code Camp 2011 - ASP.NET 4.5
 
Code igniter overview
Code igniter overviewCode igniter overview
Code igniter overview
 

More from Hossein Zahed

Machine Learning with ML.NET
Machine Learning with ML.NETMachine Learning with ML.NET
Machine Learning with ML.NETHossein Zahed
 
8 Database Paradigms
8 Database Paradigms8 Database Paradigms
8 Database ParadigmsHossein Zahed
 
مبانی رایانش ابری
مبانی رایانش ابریمبانی رایانش ابری
مبانی رایانش ابریHossein Zahed
 
HTTPS نحوه کارکرد پروتکل
HTTPS نحوه کارکرد پروتکلHTTPS نحوه کارکرد پروتکل
HTTPS نحوه کارکرد پروتکلHossein Zahed
 
مبانی چابکی و اسکرام
مبانی چابکی و اسکراممبانی چابکی و اسکرام
مبانی چابکی و اسکرامHossein Zahed
 
آموزش سی شارپ - بخش 1
آموزش سی شارپ - بخش 1آموزش سی شارپ - بخش 1
آموزش سی شارپ - بخش 1Hossein Zahed
 
فرآیند توسعه نرم افزار
فرآیند توسعه نرم افزارفرآیند توسعه نرم افزار
فرآیند توسعه نرم افزارHossein Zahed
 
مبانی اینترنت
مبانی اینترنتمبانی اینترنت
مبانی اینترنتHossein Zahed
 
تخته سیاه آنلاین
تخته سیاه آنلاینتخته سیاه آنلاین
تخته سیاه آنلاینHossein Zahed
 
مفاهیم اساسی برنامه نویسی کامپیوتر
مفاهیم اساسی برنامه نویسی کامپیوترمفاهیم اساسی برنامه نویسی کامپیوتر
مفاهیم اساسی برنامه نویسی کامپیوترHossein Zahed
 
Network Essentials v2.0
Network Essentials v2.0Network Essentials v2.0
Network Essentials v2.0Hossein Zahed
 
.Net Framework Basics
.Net Framework Basics.Net Framework Basics
.Net Framework BasicsHossein Zahed
 

More from Hossein Zahed (13)

Machine Learning with ML.NET
Machine Learning with ML.NETMachine Learning with ML.NET
Machine Learning with ML.NET
 
8 Database Paradigms
8 Database Paradigms8 Database Paradigms
8 Database Paradigms
 
مبانی رایانش ابری
مبانی رایانش ابریمبانی رایانش ابری
مبانی رایانش ابری
 
HTTPS نحوه کارکرد پروتکل
HTTPS نحوه کارکرد پروتکلHTTPS نحوه کارکرد پروتکل
HTTPS نحوه کارکرد پروتکل
 
مبانی چابکی و اسکرام
مبانی چابکی و اسکراممبانی چابکی و اسکرام
مبانی چابکی و اسکرام
 
آموزش سی شارپ - بخش 1
آموزش سی شارپ - بخش 1آموزش سی شارپ - بخش 1
آموزش سی شارپ - بخش 1
 
فرآیند توسعه نرم افزار
فرآیند توسعه نرم افزارفرآیند توسعه نرم افزار
فرآیند توسعه نرم افزار
 
مبانی اینترنت
مبانی اینترنتمبانی اینترنت
مبانی اینترنت
 
تخته سیاه آنلاین
تخته سیاه آنلاینتخته سیاه آنلاین
تخته سیاه آنلاین
 
مفاهیم اساسی برنامه نویسی کامپیوتر
مفاهیم اساسی برنامه نویسی کامپیوترمفاهیم اساسی برنامه نویسی کامپیوتر
مفاهیم اساسی برنامه نویسی کامپیوتر
 
Network Essentials v2.0
Network Essentials v2.0Network Essentials v2.0
Network Essentials v2.0
 
.Net Framework Basics
.Net Framework Basics.Net Framework Basics
.Net Framework Basics
 
Network Essentials
Network EssentialsNetwork Essentials
Network Essentials
 

Recently uploaded

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 

Recently uploaded (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

ASP.NET MVC 5 - EF 6 - VS2015

  • 1. ASP.NET MVC 5 VS2015 – EF 6 Hossein Zahed (MCP – MCTS – MCPD – MBA) http://www.hzahed.com Hossein.aspx@gmail.com
  • 2. Introduction to ASP.NET MVC 5 • ASP.NET Overview • Basics of MVC • Creating a Sample Project • Controllers • Views • Models • Forms &Validations • Razor & HTML Helpers • Model Binder • Bootstrap • Scaffolding • Ajax & jQuery • Routes • WebAPI
  • 5. ASP.NET Web Forms Features • Event DrivenTechnology • Rich controls and tools • Postbacks (Forms) • ViewState (Hidden Input) • Less Control over the HTML • Hard toTest • Rapid Development (RAD) • Sophisticated Built-in Security Features
  • 6. ASP.NET MVC Features • More Control over HTML • No Code Behind • Separation of Concerns • Easy toTest • URL Routing • Less Built-in Security Features • No Postbacks • NoViewStates • NoToolbox Server Controls
  • 9. Creating a Sample Project (1)
  • 10. Creating a Sample Project (2)
  • 11. Creating a Sample Project (3)
  • 12. Creating a Sample Project (4)
  • 13. Creating a Sample Project (5)
  • 14. Controller Basics •Controllers are classes • Derives from base System.Web.Controller class • Generates the response to the all requests •Actions are methods • They are public • Cannot be overloaded • Cannot be static • Returns an ActionResult
  • 17. Controller –Types • MVC Controllers • Empty • With Read/Write Actions • WithViews, using Entity Framework • Controllers Naming: • Place it in Contollers Folder • SampleController.cs
  • 18. Controller – Action Parameters •Empty (No parameter) •QueryString Based •string, int, double, datetime, … Single or Multiple Parameters as •Url Based (Convention) •int id => Special Parameter
  • 19. Controller – Action Results • ActionResult  General • ViewResult View (Conventions) • PartialViewResult  PartialView • RedirectResult  Redirect • RedirectToRouteResult  RedirecToAction / RedirectToRoute • ContentResult  Content (Equivalent) • JsonResult  Json (Json.Net) • JavaScriptResult  JavaScript (Ajax & jQuery Senarios) • FileResult  File (MimeTypes) • EmptyResult  (None)
  • 20. View
  • 21. View – Basics •Views provide User Interface (UI) •Visual Design of the website •Views are HTML + CSS + JavaScript + C# codes combined •Views are not directly accessible! •Controllers pass data to Views to present it to the user.
  • 22. View – Naming Conventions •In Home Controller: public ActionResult MyPage() { … returnView(); //Searches forViews/Home/MyPage.cshtml returnView(“OtherPage”); //Searches forViews/Home/OtherPage.cshtml }
  • 23. View – Passing Data from Controller to View 1.ViewBag • Passing tiny bit of data • Has some limitations • LoosingVS IntelliSense 2.StronglyTyped Data • Passing data objects • No limitation • VS IntelliSense works perfectly
  • 24. View – Passing Data Mechanism • ViewDataDictionary • A specialized dictionary class to hold different types of data • ViewData • An instance ofViewDataDictionary to read/write data to the dictionary • ViewBag (More common) • A dynamic wrapper forViewData • ViewBag.Message ≈ViewData[“Message”] • ViewBag.Message = “Hello MVC”; • ViewData[“Message”] = “Hello MVC”;
  • 25. View –ViewBag • Set (Write) – in Controller • ViewBag.Message = “Hello MVC”; • ViewBag.CurrentTime = DateTime.Now; • Any data type is accepted! • Get (Read) – inView • @ViewBag.Message • @ViewBag.CurrentTime • IntelliSense doesn’t help you!
  • 26. View –ViewBag Limitations • In Controller: • List<Book> books = new List<Book>(); • Adding some book objects to books • ViewBag.Books = books; • returnView(); • InView • @Foreach (Book b in (ViewBag.Books as IEnumerable<Book>)) (1) OR • @Foreach (dynamic b inViewBag.Books) • b. … (2) • (1): We should cast Dynamic data type before to loop in items! • (2): IntelliSense doesn’t offer any suggestions!
  • 27. View – StronglyTypedViews • In Controller: • List<Book> books = new List<Book>(); • Adding some book objects to books • returnView(books); • InView • @using MvcApplication1.Models • @model IEnumrable<Book> • @Foreach (Book b in Model) • Remember: Only one type of data can be passed to the view!
  • 28. View –View Models Need • Some times we need to transfer multiple types of data toView • In Controller: public ActionResult Edit(int id = 0) { Book book = db.Books.Find(id); if (book == null) { return HttpNotFound(); } ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", book.CategoryId); returnView(book); }
  • 29. View –View Models • Creating additional complicated models for some views • In Models: public class ShoppingCartViewModel { public IEnumerable<Product> Products { get; set; } public decimal CartTotal { get; set; } public string Message { get; set; } } • InView: • @model ShoppingCartViewModel
  • 30. View – Adding aView • Adding a newView: • Create an Action in a Controller • Right click on the Action name • AddView • SelectView Name • Select Scaffolding Template • Model class • Data context class (Entity Framework) • Reference Script Libraries (required jQuery libraries for validations) • Create as a Partial View (a view without any master page / layout) • Use a Layout Page (select a layout page, Default: _layout.cshtml)
  • 31. View – ScaffoldingTemplates • Generates a view based on the selected model type • Scaffolding Templates: • Empty • List • Create • Details • Edit • Delete • Empty (without model)
  • 32. View – RazorView Engine • One of the most requested suggestions received by MVC Team • Effectively minimizes the amount of syntax and extra characters • Razor sign is @ • Switches from HTML to C# • Previously was WebFormsView Engine <% … %> • Don’t overthink it, It JustWorks!!!
  • 33. View – RazorView Engine Reference • Code Blocks: @{ int x = 10; string name = “Mike”; } •Expression: <span>@model.Message</span>
  • 34. View – RazorView Engine Reference •Combining Code & Markup: @foreach(var item in items) { <span>@item.Prop</span> } •Combining Code & PlainText: @if (foo) { <text>PlainText</text> }
  • 35. View – RazorView Engine Reference •Combining Code & Plain Text (alternate): @if (foo) { @:PlainText is @bar } •Using Blocks: @ using (Html.BeginForm()) { <input type="text" value="input here"> }
  • 36. View – RazorView Engine Reference •Email Address: My email address is hossein.aspx@gmail.com •Server Side Comment: @* This is a server side multiline comment *@
  • 37. View – RazorView Engine Reference •Calling a Generic Method: @(MyClass.MyMethod<AType>()) •Url Resolution withTilde: <script src=“~/content/jquery.js”></script> • At Sign: • If you need at sign itself Use @@ instead • ATwitter handle: follow me @@Hossein.aspx • @section & @RenderSection
  • 38. View –ViewStart •_ViewStart.cshtml • Applies the default Layout page for all views • Removes the redundancy @{ Layout = "∼/Views/Shared/_Layout.cshtml"; }
  • 39. View – Specifying a PartialView •An stand alone full view •No _layout.cshtml •Specified in the Controller: public ActionResult Message() { ViewBag.Message = "This is a partial view."; return PartialView(); }
  • 40. View – HTML Encoding • Potential Cross-Site Scripting Injections (XSS) • Razor automatically Encodes all Html Outputs • InView: @{ string message = "<script>alert('hacked!');</script>"; } <span>@message</span> • Show in Browser’s Source Code Page: <span><script>alert(&#39;hacked!&#39;);</script></span>
  • 41. Model
  • 42. Model – Basics •Models contain all application core (Business Logic,Validation Login, Data Access Login) •Models are C# classes •Models hold and manipulate application data •Models are placed in the Models folder •Models define relationships between classes •Models map C# classes to database tables
  • 43. Model – Conventions •Model classes doesn’t have any constructor •Model classes and their properties must be public •public int Id generates P.K and Identity in database •Virtual accessor for properties is used to define relations between classes •1:1 , 1:n , n:n relations can be defined in models
  • 44. Model – Data Annotations • DataType: Specify the datatype of a property • DisplayName: Specify the display name for a property. • DisplayFormat: Specify the display format for a property like different format for Date proerty. • Required: Specify a property as required. • ReqularExpression: Validate the value of a property by specified regular expression pattern. • Range:Validate the value of a property with in a specified range of values. • StringLength: Specify min and max length for a string property. • MaxLength: Specify max length for a string property. • ScaffoldColumn: Specify fields for hiding from editor forms. • Bind: Specify fields to include or exclude when adding parameter or form values to model properties. (Class specific data annotation)
  • 45. Model – Code First vs Database First
  • 46. Model – Code First (Model First) • The Code First approach allows us to define the model from the code without generating classes that are generally coupled with the framework. • In code first, model objects are defined with POCOs , "Plain Old CLR Objects". POCOs are simple plain classes that have no inheritance and do not implement interfaces. We can automatically generate the database from them, or we can use an existing database and generate the class mapping from the code. • The benefits of using this approach is that the Model remains independent from the persistence framework (in this case, Entity Framework), as the POCOs classes are not coupled with the mapping framework.
  • 47. Model – Code First Implimentation • 1. Create a Database in MSSQL Server (Version Independent) • 2. Configuring "DefaultConnection" ConnectionString in Web.Config • 3. Nuget Package Manager Console: enable-migrations • 4. DbSet in IndentityModel.cs => ApplicationDbContext • 5. Nuget Package Manager Console: add-migration InitialCreate • 6. Nuget Package Manager Console: update-database -targetmigration InitialCreate • 7. Seed Method => Adding objects • 8. Follow the Step 6 again
  • 48. Model – Scaffolding • The term "Scaffolding" is used by many software technologies to mean "quickly generating a basic outline of your software that you can then edit and customize". • ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications.Visual Studio 2013 includes pre-installed code generators for MVC andWeb API projects.You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project.
  • 49. Model –What is Scaffolding? • The term "Scaffolding" is used by many software technologies to mean "quickly generating a basic outline of your software that you can then edit and customize". • ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications.Visual Studio 2013 includes pre-installed code generators for MVC andWeb API projects.You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project.
  • 50. Model – Scaffolding – Step 1
  • 51. Model – Scaffolding – Step 1
  • 52. Model – Scaffolding – Step 3
  • 53. Model – Scaffolding – Step 4
  • 55. Bootstrap –What is Bootstrap? • Bootstrap is the most popular HTML,CSS, and JavaScript framework for developing responsive, mobile-first web sites. • Bootstrap is completely free to download and use! • Bootstrap is a free and open-source collection of tools for creating websites and web applications. It contains HTML- and CSS-based design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extensions.The bootstrap framework aims to ease web development. • Bootstrap is a front end, that is an interface between the user and the server-side code which resides on the "back end" or server. And it is a web application framework, that is a software framework which is designed to support the development of dynamic websites and web applications. • As of March 2015, it was the most-starred project on GitHub, with over 78,000 stars and more than 30,000 forks.
  • 56. Bootstrap –Why use Bootstrap? •Easy to use: Anybody with just basic knowledge of HTML and CSS can start using Bootstrap •Responsive features: Bootstrap's responsive CSS adjusts to phones, tablets, and desktops •Mobile-first approach: In Bootstrap 3, mobile-first styles are part of the core framework •Browser compatibility: Bootstrap is compatible with all modern browsers (Chrome, Firefox, Internet Explorer, Safari, and Opera)
  • 57. Bootstrap –Where to get Bootstrap? •Download Bootstrap from getbootstrap.com •Include Bootstrap from a CDN bootstrapcdn.com •Nuget Package Console: PM> Install-PackageTwitter.Bootstrap.MVC
  • 58. Bootstrap –Where to get Bootstrap? •Download Bootstrap from getbootstrap.com •Include Bootstrap from a CDN bootstrapcdn.com •Nuget Package Console: PM> Install-PackageTwitter.Bootstrap.MVC
  • 59. Bootstrap – Creating the first page – Step 1 •1. Add the HTML5 doctype: Bootstrap uses HTML elements and CSS properties that require the HTML5 doctype. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> </html>
  • 60. Bootstrap – Creating the first page – Step 2 •2. Bootstrap 3 is mobile-first: Bootstrap 3 is designed to be responsive to mobile devices. Mobile-first styles are part of the core framework. <meta name="viewport" content="width=device-width, initial-scale=1"> •The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device). •The initial-scale=1 part sets the initial zoom level when the page is first loaded by the browser.
  • 61. Bootstrap – Creating the first page – Step 3 •3. Containers: Bootstrap also requires a containing element to wrap site contents.There are two container classes to choose from: •The .container class provides a responsive fixed width container •The .container-fluid class provides a full width container, spanning the entire width of the viewport
  • 62. Bootstrap – Creating the first page – Sample <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h1>My First Bootstrap Page</h1> <p>This is some text.</p> </div> </body> </html>
  • 63. Bootstrap – Components Grid System Button Dropdowns Tooltip Typography Button Groups Tabs/Pills Popover Tables Progress Bars Navbar Images Pagination Froms Jumbotron Pager Inputs Wells List Groups Carousel Glyphicons Panels Modal
  • 64. Forms
  • 65. Forms – Using Forms • The form tag is powerful. Without the form tag, the Internet would be a read-only repository of boring documentation.You wouldn't be able to search the web or buy anything (even this book) over the Internet. If an evil genius stole all the form tags from every website tonight, civilization would crumble by lunchtime tomorrow. • A form is a container for input elements: buttons, checkboxes, text inputs, and more. • The two most important attributes of a form tag are the action and the method attributes. • Many developers coming to the MVC framework have been using ASP.NET Web Forms. Web Forms don't expose the full power of the form tag (you could sayWeb Forms manage and exploit the form tag for their own purposes). It's easy to excuse the Web Forms developer who forgets what the form tag is capable of—such as creating an HTTP GET request.
  • 66. Forms – Action • The action attribute tells a web browser where to send the information, so naturally the action contains a URL.The URL can be relative, or in cases where you want to send information to a different application or a different server, the action URL can also be an absolute URL. • The following form tag sends a search term (the input named q) to the Bing search page from any application: <form action="http://www.bing.com/search"> <input name="q" type="text" /> <input type="submit" value="Search!" /> </form>
  • 67. Forms – Method (GET or POST) • The form tag in the preceding code snippet does not include a method attribute.The method attribute tells the browser whether to use an HTTP POST or HTTP GET when sending the information.You might think the default method for a form is HTTP POST. After all, you regularly POST forms to update your profile, submit a credit card purchase, and leave comments on the funny animal videos onYouTube. However, the default method value is GET, so by default a form sends an HTTP GET request: <form action="http://www.bing.com/search" method="get"> <input name="q" type="text" /> <input type="submit" value="Search!" /> </form> Result: http://www.bing.com/search?q=love
  • 68. Forms –To GET or to POST? • Web applications generally use GET requests for reads and POST requests for writes (which typically include updates, creates, and deletes). • A request to pay for music uses POST. • A request to search for music, a scenario you look at next, uses GET. • In a GET request, the browser puts all the input values into a query string. • In a POST request, the browser places all the input values inside the body of the HTTP request.
  • 69. Forms – Html Helper for From @using (Html.BeginForm("Search", "Home", FormMethod.Get)) { <input type="text" name="q" /> <input type="submit" value="Search" /> } • The BeginForm HTML helper asks the routing engine how to reach the Search action of the HomeController. Behind the scenes it uses the method named GetVirtualPath on the Routes property exposed by RouteTable - that's where your web application registered all its routes in global.asax.
  • 70. HTML Helpers – Introduction • HTML helpers are methods you can invoke on the Html property of a view. You also have access to URL helpers (via the Url property), and Ajax helpers (via the Ajax property). All these helpers have the same goal, to make views easy to author.The URL helper is also available from within the controller. • Most of the helpers, particularly the HTML helpers, output HTML markup. For example, the BeginForm helper you saw earlier is a helper you can use to build a robust form tag for your search form. • Note the BeginForm helper outputs both the opening <form> and the closing </form>.The helper emits the opening tag during the call to BeginForm, and the call returns an object implementing IDisposable.
  • 71. HTML Helpers – More Control • While protecting you, helpers can also give you the level of control you need. As an example of what you can achieve with helpers, look at another overloaded version of the BeginForm helper: @using (Html.BeginForm("Search", "Home", FormMethod.Get, new { target = "_blank", @class="editForm", data_validatable=true })) Result: <form action="/Home/Search" class="editForm" data-validatable="true" method="get" target="_blank">
  • 72. HTML Helpers – Common Helpers Helper HTML Element Html.CheckBox <input type="checkbox" /> Html.DropDownList <select></select> Html.Hidden <input type="hidden" /> Html.Label <label for="" /> Html.ListBox <select></select> or <select multiple></select> Html.Password <input type="password" /> Html.RadioButton <input type="radio" /> Html.TextArea <textarea></textarea> Html.TextBox <input type="text" /> Html.ValidationMessage <span></span>
  • 73. HTML Helpers – StronglyTyped Helpers Helper HTML Element Html.CheckBoxFor <input type="checkbox" /> Html.DropDownListFor <select></select> Html.HiddenFor <input type="hidden" /> Html.LabelFor <label for="" /> Html.ListBoxFor <select></select> or <select multiple></select> Html.PasswordFor <input type="password" /> Html.RadioButtonFor <input type="radio" /> Html.TextAreaFor <textarea></textarea> Html.TextBoxFor <input type="text" /> Html.ValidationMessageFor <span></span>
  • 74. HTML Helpers - Model State • All the helpers you use to display form values also interact with ModelState. Remember, ModelState is a byproduct of model binding and holds all validation errors detected during model binding. Model state also holds the raw values the user submits to update a model. • Helpers used to render form fields automatically look up their current value in the ModelState dictionary.The helpers use the name expression as a key into the ModelState dictionary. If an attempted value exists in ModelState, the helper uses the value from ModelState instead of a value in view data. • The ModelState lookup allows bad values to preserve themselves after model binding fails. For example, if the user enters the value abc into the editor for a DateTime property, model binding will fail and the value abc will go into model state for the associated property.When you re-render the view for the user to fix validation errors, the value abc will still appear in the DateTime editor, allowing the users to see the text they tried as a problem and allowing them to correct the error. • When ModelState contains an error for a given property, the form helper associated with the error renders a CSS class of input-validation-error in addition to any explicitly specified CSS classes.The default style sheet, style.css, included in the project template contains styling for this class.
  • 75. URL Helpers • The URL helpers are similar to the HTML ActionLink and RouteLink helpers, but instead of returning HTML they build URLs and return the URLs as strings.There are three helpers: • Action • Content • RouteUrl • The Action URL helper is exactly like ActionLink, but does not return an anchor tag. For example, the following code displays the URL (not a link) to browse all book categories in the store: <span> @Url.Action("Browse", "Store", new { category= "ASP.NET" }, null) </span> • The result is the following HTML: <span> /Store/Browse?category=asp.net </span>
  • 76. URL Helpers • The RouteUrl helper follows the same pattern as the Action helper, but like RouteLink it accepts a route name and does not have arguments for controller name and action name. The Content helper is particularly helpful because it can convert a relative application path to an absolute application path.You'll see the Content helper at work in the Book Store's _Layout view. <script src="@Url.Content("∼/Scripts/jquery-1.10.2.min.js")“ type="text/javascript"></script> • Using a tilde (~) as the first character in the parameter you pass to the Content helper lets the helper generate the proper URL no matter where your application is deployed (think of the tilde as representing the application root directory).Without the tilde, the URL could break if you moved the application up or down the virtual directory tree. • InASP.NET MVC 5, which uses Razor version 3, the tilde character is resolved automatically when it appears in the src attribute for script, style, and img elements.The code in the previous example could also be written as follows and work just fine: <script src="∼/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
  • 77. Ajax
  • 78. Ajax – Introduction to jQuery? • The jQuery “write less, do more” tagline is a perfect description of the jQuery experience. • The API is terse yet powerful.The library itself is flexible yet lightweight. • Best of all, jQuery supports all the modern browsers (including Internet Explorer, Firefox, Safari, Opera, and Chrome), and hides the inconsistencies (and bugs) you might experience if you wrote code directly against the API each browser provides. • jQuery is one of the most popular JavaScript libraries in existence, and remains an open source project. • www.jquery.com
  • 79. Ajax – jQuery Features •jQuery excels at finding, traversing, and manipulating HTML elements inside an HTML document. •After you've found an element, jQuery also makes it easy to wire up event handlers on the element, animate the element, and build Ajax interactions around the element
  • 80. Ajax – jQuery Selectors •Selectors are the strings you pass to the jQuery function to select elements in the DOM. Selector Description $("#header") Find the element with an id of “header" $(".editor-label") Find all elements with a class name of “.editor-label" $("div") Find all <div> elements $("#header div") Find all <div> elements that are descendants of the element with an id of “header" $("#header > div") Find all <div> elements that are children of the element with an id of “header" $("a:even") Find evenly numbered anchor tags
  • 81. Ajax – jQuery Example 1 $(function () { $("#album-list img").mouseover(function () { $(this).animate({ height: "+=25', width: "+=25" }) .animate({ height: "-=25', width: "-=25" }); }); });
  • 82. Ajax – jQuery Example 2 $("a").mouseover(function () { $(this).addClass("highlight"); }).mouseout(function () { $(this).removeClass("highlight"); });
  • 83. Ajax – jQuery Shortcuts •All the jQuery methods you use against a wrapped set, like the mouseover method, return the same jQuery wrapped set.This means you can continue invoking jQuery methods on elements you've selected without reselecting those elements.We call this method chaining. •Shortcuts are available in jQuery for many common operations. Setting up effects for mouseover and mouseout is a common operation, and so is toggling the presence of a style class.
  • 84. Ajax – jQuery Example 3 $("a").hover(function () { $(this).toggleClass("highlight"); });
  • 85. Ajax & jQuery • jQuery includes everything you need to send asynchronous requests back to your webserver.You can generate POST requests or GET requests and jQuery notifies you when the request is complete (or if there is an error).With jQuery, you can send and receive XML data (the x in Ajax stands for XML, after all), but as you'll see in this chapter, consuming data in HTML, text, or JavaScript Object Notation (JSON) format is trivial. jQuery makes Ajax really easy. • In fact, jQuery makes so many things easy it has changed the way web developers write script code.
  • 86. Ajax – Unobtrusive JavaScript • Unobtrusive JavaScript is the practice of keeping JavaScript code separate from markup.You package all the script code you need into .js files. If you look at the source code for a view, you don't see any JavaScript intruding into the markup. Even when you look at the HTML rendered by a view, you still don't see any JavaScript inside.The only sign of script you'll see is one or more <script> tags referencing the JavaScript files. • Old way sample: <div onclick="javascript:alert('click');">Testing, testing</div>
  • 87. Ajax – MVC & jQuery •jQuery is in MVC projects by default •jQuery can be downloaded from Nuget •jQuery is being bundled in BundleConfig.cs •@section Scripts •List of default JavaScript files in the Script folder
  • 88. Ajax Helpers • The Ajax functionality of the Ajax helpers will not work without a reference to the jquery.unobtrusive-ajax.js script. If you're having trouble with the Ajax helpers, this is the first thing you should check. • Adding the Unobtrusive Ajax Script toYour Project: • Microsoft jQuery Unobtrusive Ajax Nuget Package • Install- Package Microsoft.jQuery.Unobtrusive.Ajax • Adding <script src="~/Scripts/jquery.unobtrusive- ajax.min.js"> </script> after jQuery
  • 89. Ajax Helpers - @Ajax.ActionLink <div id="dailydeal"> @Ajax.ActionLink("View Deals", "DailyDeal", null, new AjaxOptions { UpdateTargetId = "dailydeal", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }, new {@class = "btn btn-primary"}) </div> Controller: public ActionResult DailyDeal() { var album = GetDailyDeal(); return PartialView("_DailyDeal", album); }
  • 90. Ajax Helpers – Rendered Markup <div id="dailydeal"> <a class="btn btn-primary" data-ajax="true" data-ajax- method="GET " data-ajax-mode="replace" data-ajax- update="#dailydeal" href="/Home/DailyDeal"> View Deals </a> </div>
  • 91. Ajax Helpers – @Ajax.Form @using (Ajax.BeginForm(“BookSearch", "Home", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "GET", OnFailure = "searchFailed", LoadingElementId = "ajax-loader", UpdateTargetId = "searchresults", })) { <input type="text" name="q" /> <input type="submit" value="search" /> <img id="ajax-loader" src="@Url.Content("~/Images/ajax-loader.gif") " style="display:none" /> } <div id="searchresults"></div>
  • 92. Ajax Helpers – @Ajax.Form Controller: public ActionResult ArtistSearch(string q) { var artists = GetArtists(q); return PartialView(artists); } Failure JavaScript: function searchFailed() { $("#searchresults").html("Sorry, there was a problem with the search."); }
  • 93. Ajax Helpers – @Ajax.Form View: @model IEnumerable<MvcMusicStore.Models.Artist> <div id="searchresults"> <ul> @foreach (var item in Model) { <li>@item.Name</li> } </ul> </div>
  • 94. Ajax – jQueryValidations • By default, unobtrusive JavaScript and client-side validation are enabled in an ASP.NET MVC application. However, you can change the behavior through web.config settings. If you open the root-level web.config file in a new application, you'll see the following appSettings configuration section: <appSettings> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings> • If you want to turn off either feature throughout the application, you can change either setting to false. In addition, you can also control these settings on a view-by view basis.The HTML helpers EnableClientValidation and EnableUnobtrusiveJavascript override the configuration settings inside a specific view. • The primary reason to disable either feature is to maintain backward compatibilitywith custom scripts.
  • 96. Security – Web Form Features • Server Components automatically HTML encode displayed values and attributes to help prevent XSS attacks. • ViewState is encrypted and validated to help prevent tampering with form posts. • RequestValidation (<% @page validaterequest="true" %>) intercepts maliciouslookingdata and offers a warning (this is still turned on by default with ASP.NET MVC). • EventValidation helps prevent injection attacks and posting of invalid values.
  • 97. Security – MVC Way • ASP.NET MVC gives you more control over markup and how your application functions, which means you've taken on more responsibility. • To be clear, ASP.NET MVC does offer you a lot of built-in protection (for example, features like HTML encoding by default use HTML helpers and Razor syntax, request validation, and use scaffolded controllers whitelist form elements to prevent over-posting attacks). • However, you can easily shoot yourself in the foot if you don't understand web • Never, ever trust any data your users give you!
  • 98. Security – Some Practical Examples (1) • Any time you render data that originated as user input, encode it. The most common practice is to HTML encode it, though you sometimes need to HTML attribute encode it if it's displayed as an attribute value, or JavaScript encode it if it's being used in a JavaScript code snippet. And sometimes you need multiple layers of encoding, such as a JavaScript code snippet in an HTML page. • Think about what portions of your site should be available for anonymous access, and require authentication on the others. • Don't try to sanitize your users' HTML input yourself (using regular expressions or some other method)—you'll lose.
  • 99. Security – Some Practical Examples (2) • Use HTTP-only cookies when you don't need to access cookies via client-side script (which is most of the time). • Remember that external input isn't just obvious form fields; it includes URL query string values, hidden form fields, Ajax requests, results of external web services you're using, and more. • Consider using the AntiXSS encoder (a component of the MicrosoftWeb Protection Library, which is now distributed with ASP.NET 4.5 and higher).
  • 100. Security – Conclusion You have users and enemies, and they are waiting for you to build this application of yours so they can come and break into it. Hackers, crackers, spammers, viruses, malware, they all want access to your application and the files on it. If you haven't faced this before, it's usually for one of two reasons: •You haven't built an application yet. •You didn't find out that someone hacked your application.
  • 101. Authentication & Authorization Sometimes people get confused with respect to the difference between user authentication and user authorization. Getting these concepts confused is easy to do, but in summary: • Authentication is verifying that users are who they say they are, using some form of login mechanism (username/password, OpenID, OAuth and so on—something that says “this is who I am”). • Authorization is verifying that they can do what they want to do with respect to your site.This is usually achieved using some type of role-based or claim-based system.
  • 102. Authorize Attribute • The first, simplest step in securing an application is requiring that a user be logged in to access specific parts of the application.You can do that using the Authorize action filter on a controller, on specific actions within a controller, or even globally for the entire application. • The AuthorizeAttribute is the default authorization filter included with ASP.NET MVC. Use it to restrict access to an action method. Applying this attribute to a controller is shorthand for applying it to every action method within the controller.
  • 103. Authorize Attribute – Best Practice A good approach to security is to always put the security check as close as possible to the thing you are securing.You might have other checks higher up the stack, but ultimately, you want to secure the actual resource.This way, no matter how the user got to the resource, there will always be a security check. In this case, you don't want to rely on routing and URL authorization to secure a controller; you really want to secure the controller itself.The AuthorizeAttribute serves this purpose. • If you don't specify any roles or users, the current user must simply be authenticated in order to call the action method.This is an easy way to block unauthenticated users from a particular controller action. • If a user attempts to access an action method with this attribute applied and fails the authorization check, the filter causes the server to return a “401 Unauthorized” HTTP status code.
  • 104. Securing Controller Actions [Authorize] publicActionResult Buy(int id) { var album = GetAlbums().Single(a => a.AlbumId == id); returnView(album); }
  • 105. Using URL Authorization • A common means of securing an application withWeb Forms is to use URL authorization. For example, if you have an admin section and you want to restrict it to users who are in the Admins role, you might place all your admin pages in an admin folder and deny access to everyone except those in the Admins role to that subfolder. • With ASP.NETWeb Forms, you can secure a directory on your site by locking it down in the web.config. • If you want to keep secure all the files in a directory, you should secure the whole directory with Web Forms!
  • 106. Using URL Authorization – Web.Config <location path= "Admin" allowOverride="false"> <system.web> <authorization> <allow roles= "Administrator" /> <deny users="?" /> </authorization> </system.web> </location> With MVC this approach won't work so well for two reasons: • Requests no longer map to physical directories. • There may be more than one way to route to the same controller.
  • 107. Account Controller It's nice that the AccountController - and its associated views - are all provided in the ASP.NET MVC with the individual user accounts authentication template. In simple cases, adding authorization doesn't require any additional code or configuration. Equally nice, though, is that you can change any of those parts: • The AccountController (as well as the associatedAccount models and views) is a standard ASP.NET MVC controller, which is pretty easy to modify. • The authorization calls work against standard OWIN middleware components published in the ASP.NET Identity system.You can switch authentication middleware components or write your own. • The AuthorizeAttribute is a standard authorization attribute, implementing IAuthorizeFilter.You can create your own authorization filters.
  • 108. Securing Entire Controllers • The earlier scenario demonstrated a single controller with the AuthorizeAttribute applied to specific controller actions. • You may want to secure an entire Contoller. In this case you can put the AuthorizeAttribute on the Contoller. [Authorize] public class CheckoutController : Controller
  • 109. Securing Entire Application using a Global Authorization Filter • For many sites, nearly the entire application should require authorization. In this case, requiring authorization by default and making exceptions in the few places where anonymous access is allowed—such as the site's home page and URLs required for the login process—is simpler. • For this case, configuring the AuthorizeAttribute as a Global Filter and allowing anonymous access to specific controllers or methods using the AllowAnonymous attribute is a good idea. • Global Authorization Is Global Only to MVC. Keep in mind that a global filter applies only to MVC controller actions. It doesn't secure Web Forms, static content, or other ASP.NET handlers.
  • 110. Global Authorization Filter • To register the AuthorizeAttribute as a global filter, add it to the global filters collection in the RegisterGlobalFilters method, located in App_StartFilterConfig.cs: public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new System.Web.Mvc.AuthorizeAttribute()); filters.Add(new HandleErrorAttribute()); } • This applies the AuthorizeAttribute to all controller actions in the application. • To allow an exception for a Controller or Action you can put [AllowAnonymous]
  • 111. Specify Roles & Users with AuthorizeAttribute If you need the ability to limit access to specific roles or users. Fortunately, AuthorizeAttribute allows you to specify both roles and users, as shown here: [Authorize(Roles="Administrator")] public class StoreManagerController : Controller [Authorize(Roles="Administrator,SuperAdmin")] public class TopSecretController:Controller [Authorize(Users="Jon,Phil,Scott,Brad,David")] public class TopSecretController:Controller [Authorize(Roles="SuperAdmin", Users="Jon,Phil,Brad,David")] public class TopSecretController:Controller
  • 112. Managing users and roles in User Identity One of the design requirements forASP.NET Identity is to allow for extensive customization without undue pain. Some of the extensibility points include: 1. Adding additional user profile data is now trivial. 2. Persistence control is supported through the use of UserStore and RoleStore abstractions over the data access layer. 3. The RoleManager makes it easy to create roles and manage role membership.
  • 113. 1. Storing Additional User Profile Data It's a very common requirement to store additional information about your users: birthday,Twitter handle, site preferences, etc. In the past, adding additional profile data was unnecessarily difficult. In ASP.NET Identity, users are modeled using an Entity Framework Code First model, so adding additional information to your users is as simple as adding properties to your ApplicationUser class (found in /Models/IdentityModels.cs). For example, to add an Address andTwitter handle to your user, youd just add the following properties: public class ApplicationUser : IdentityUser { public string Address { get; set; } public stringTwitterHandle { get; set; } } More Details: http://go.microsoft.com/fwlink/?LinkID=317594
  • 114. 2. Persistence Control • By default, ASP.NET Identity implements data storage using Entity Framework Code First, so you can customize the data storage in any way you'd normally configure Entity Framework (e.g. pointing the connection string at any database Entity Framework supports.) • Additionally, ASP.NET Identity's data storage is built on top of the UserStore and RoleStore abstractions.You can implement your own UserStore and / or RoleStore to persist your data in any way you'd like, including AzureTable Storage, custom file formats, web service calls, etc. • This tutorial explains the concepts in detail, with a link to an example using MySQL: http://www.asp.net/identity/overview/extensibility/overview-of- custom-storageproviders-for-aspnet-identity
  • 115. 3. Persistence Control • ASP.NET Identity includes a UserManager and RoleManager which make it easy to perform common tasks like creating users and roles, adding users to roles, checking if a user is in a role, etc. • A detailed example is available here: http://azure.microsoft.com/enus/ documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-app- membership-oauthsql-database/ • It's great that you've got these extensibility points when you need them. For the most part, if you're using the standard AccountController and storing user information via Entity Framework, you just code away without considering the extensibility points—until you want them.
  • 116. EXTERNAL LOGINVIA OAUTH AND OPENID • Historically, the huge majority of web applications have handled authorization based on a locally maintained account database. • Although traditional membership is a great fit in a lot of web applications, it comes with some serious downsides: • Maintaining a local database of usernames and secret passwords is a large security liability. Large security breaches involving hundreds of thousands of users‘ account information (often including unencrypted passwords) have become common.Worse, because many users reuse passwords on multiple websites, compromised accounts may affect your users' security on their banking or other sensitive websites. • Website registration is annoying. Users have gotten tired of filling out forms, complying with widely differing password policies, remembering passwords, and worrying whether your site is going to keep their information secure. A significant percentage of potential users will decide they would rather not bother with registering for your site. • Technically, the OAuth protocol was designed for authorization, but in general use it's frequently used for authentication.
  • 117. Trusted External Login Providers Supporting only providers whose security you trust, which generally means sticking with well-known providers, is important for a couple reasons: • When you are redirecting your users to external sites, you want to make sure that these sites are not malicious or poorly secured ones that will leak or misuse your users' login data or other information. • Authentication providers are giving you information about users—not just their registration state, but also e-mail addresses and potentially other provider-specific information. Although by default this additional information isn't stored, reading provider data such as e-mail to prevent the user from having to re-enter it is not uncommon. A provider could potentially—either accidentally or maliciously— return information. Displaying any provider information to the user before you store it is generally a good idea.
  • 118. Requiring SSL for Login • The callback from an external provider to your site contains security tokens that allow access to your site and contain user information.Transmitting this information over HTTPS to prevent interception while this information travels over the Internet is important. • To enforce HTTPS for this callback, applications that support external logins should require HTTPS for access to the AccountController's Login GET method using the [RequireHttps] [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } • Enforcing HTTPS during login to your site causes all calls to external providers to occur over HTTPS, which, in turn, causes the providers to make their callbacks to your site using HTTPS. • Additionally, using HTTPS with Google authentication is important. Google reports a user who logs in once via HTTP and later via HTTPS as two different people. Always requiring HTTPS prevents this problem.
  • 120. Understanding URLs Some guidelines for high-quality URLs: • Choosing a domain that is easy to remember and easy to spell • Short URLs • Easy to type URLs • URLs that reflect site structure • URLs that are hackable to allow users to move to higher levels of the information architecture by hacking off the end of the URL • Persistent URLs, which don't change
  • 121. MVC vs. Web Forms • InWeb Forms a direct relationship exists between the URL and what physically exists on disk. A request for this URL is received by the web server, which executes some code associated with this file to produce a response. • MVC generally takes a different approach by mapping the URL to a method call on a class, rather than some physical file.These classes are generally called controllers because their purpose is to control the interaction between the user input and other components of the system.The methods that serve up the response are generally called actions.These represent the various actions the controller can process in response to user input requests.
  • 122. URL vs. URI URL: Uniform Resource Locator URI: Uniform Resource Identifier • All URLs are technically URIs.TheW3C has said, at www.w3.org/TR/uriclarification/# contemporary, that a “URL is a useful but informal concept:A URL is a type of URI that identifies a resource via a representation of its primary access mechanism.” • In other words, a URI just identifies a resource, but a URL also tells you how to get it.
  • 123. Introduction to Routing Routing within the ASP.NET MVC framework serves two main purposes: • It matches incoming requests that would not otherwise match a file on the file system and it maps the requests to a controller action. • It constructs outgoing URLs that correspond to controller actions.
  • 124. Comparing Routing to URL Rewriting • The key difference is that URL rewriting is focused on mapping one URL to another URL. • For example, URL rewriting is often used for mapping old sets of URLs to a new set of URLs. Contrast that to Routing, which is focused on mapping a URL to a resource. It constructs outgoing URLs that correspond to controller actions. • Another key difference is that Routing also helps generate URLs using the same mapping rules that it uses to match incoming URLs. URL rewriting applies only to incoming requests and does not help in generating the original URL.
  • 125. Routing Approaches • MVC has always supported a centralized, imperative, code-based style of defining routes that we'll call traditional routing.This is a good option that is still fully supported. • MVC 5 adds a second option using declarative attributes on your controller classes and action methods, which is called attribute routing.This new option is simpler. • Both options work well, and both are flexible enough to handle complex routing scenarios.Which option to choose is largely a matter of style and preference.
  • 126. Defining Attribute Routes • Every ASP.NET MVC application needs routes to allow it to handle requests. • Routes are the entry points into your MVC application. • A route definition starts with a URL template, which specifies the pattern that the route will match. • Route definitions can appear as attributes on either the controller class or on an action method. • Routes can also specify constraints and default values for the various parts of the URL, providing tight control over how and when the route matches incoming request URLs. • Routes can even have names associated with them, which comes into play for outgoing URL construction (the second main purpose of Routing).
  • 127. Route URLs • Global.asax.cs  RouteConfig.RegisterRoutes(RouteTable.Routes); • App_Start  RouteConfig.cs public static void RegisterRoutes(RouteCollection routes) { routes.MapMvcAttributeRoutes(); } • Controllers  HomeController.cs [Route("about")] // RouteTemplate public ActionResult About()
  • 128. Route URLs Examples (1) • Single RouteTemplate [Route("about")] public ActionResult About() • Multiple RouteTemplate [Route("about")] [Route("home/about")] public ActionResult About()
  • 129. Route URLs Examples (2) • RouteValues [Route("book/{id}")] public ActionResult Details(int id) • Multiple RouteValues [Route("{year}/{month}/{day}")] public ActionResult Index(string year, string month, string day)
  • 130. Route URLs Examples (3) • Controller Routes [Route("home/{action}")] public class HomeController : Controller • Controller Routes + Action Routes [Route("home/{action}")] public class HomeController : Controller { [Route("home")] [Route("home/index")] public ActionResult Index()
  • 131. Route URLs Examples (4) • Route Prefix [RoutePrefix("home")] [Route("{action}")] public class HomeController : Controller { [Route("")] [Route("index")] public ActionResult Index()
  • 132. Route Constraints [Route("book/{id:int}")] public ActionResult Details(int id) { returnView(); } [Route("book/{title}")] public ActionResult Details(string title) { returnView(); }
  • 134. Route Defaults [Route("home/{action=Index}")] public class HomeController : Controller { public ActionResult Index() { returnView(); } public ActionResult About() { returnView(); } }
  • 135. Route Optional Parameter [RoutePrefix("books")] [Route("{action}/{id?}")]OR [Route("{action=Index}/{id?}")] public class BooksController : Controller { public ActionResult Index() { returnView(); } public ActionResult Details(int id) { returnView(); }
  • 136. DefiningTraditional Routes • Global.asax.cs  RouteConfig.RegisterRoutes(RouteTable.Routes); • App_Start  RouteConfig.cs public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute("simple", "{first}/{second}/{third}"); }
  • 137. DefiningTraditional Routes • RouteValues routes.MapRoute("simple", "{controller}/{action}/{id}"); • Optional Parameters routes.MapRoute("simple", "{controller}/{action}/{id}", new {id = UrlParameter.Optional}); • DefaultValues routes.MapRoute("simple", "{controller}/{action}/{id}", new { id = UrlParameter.Optional, action = "index" });
  • 138. DefiningTraditional Routes • Route Constraints routes.MapRoute("blog", "{year}/{month}/{day}", new { controller = "blog", action = "index" }, new { year = @"d{4}", month = @"d{2}", day = @"d{2}" });
  • 139. Combining Attribute Routing withTraditional Routing • Both support route templates, constraints, optional values, and defaults. • The syntax is a little different, but the functionality they offer is largely equivalent, because under the hood both use the same Routing system. • You can use either attribute routing, traditional routing, or both. • Routing checks each route in order and chooses the first route that matches. • If there's any overlap between a traditional route and an attribute route, the first route registered wins. • It is recommended to put the MapMvcAttributeRoutes call first. • Attribute routes are usually more specific, and having attribute routes come first allows them to take precedence over traditional routes, which are usually more generic.
  • 140. Choosing Attribute Routes orTraditional Routes Should you use attribute routes or traditional routes? Either option is reasonable, but here are some suggestions on when to use each one. Consider choosing traditional routes when: • You want centralized configuration of all your routes. • You use custom constraint objects. • You have an existing working application you don't want to change. Consider choosing attribute routes when: • You want to keep your routes together with your action's code. • You are creating a new application or making significant changes to an existing one.
  • 141. Catch-All Parameter • A catch-all parameter allows for a route to match part of a URL with an arbitrary number of segments. • The value put in the parameter is the rest of the URL path (that is, it excludes the query string, if any). • A catch-all parameter is permitted only as the last segment of the route. public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute("catchallroute", "query/{query-name}/{*extrastuff}"); }
  • 142. Catch-All Parameter Requests URL ParameterValue /query/select/a/b/c extrastuff = "a/b/c" /query/select/a/b/c/ extrastuff = "a/b/c/" /query/select/ extrastuff = null (Route still matches.The catch-all just catches the null string in this case.)
  • 143. Multiple Route Parameters in a Segment A route URL may have multiple parameters per segment. For example, all the following are valid route URLs: • {title}-{artist} • Album{title}and{artist} • {filename}.{ext} To avoid ambiguity, parameters cannot be adjacent. For example, the following are invalid: • {title}{artist} • Download{filename}{ext}
  • 144. Matching Route URLs with Multiple Parameters Route URL Request URL Route Data Result {filename}.{ext} /Foo.xml.aspx filename="Foo.xml"ext="aspx" My{location}-{subloc} /MyHouse-dwelling location="House“ subloc="dwelling" {foo}xyz{bar} /xyzxyzxyzblah foo="xyzxyz"bar="blah"
  • 145. StopRoutingHandler and IgnoreRoute • By default, Routing ignores requests that map to physical files on disk. That's why requests for files such as CSS, JPG, and JS files are ignored by Routing and handled in the normal manner. • However, in some situations, there are requests that don't map to a file on disk that you don't want Routing to handle. For example, requests for ASP.NET's web resource handlers, WebResource.axd, are handled by an HTTP handler and don't correspond to a file on disk. • One way to ensure that Routing ignores such requests is to use the StopRoutingHandler.
  • 146. StopRoutingHandler and IgnoreRoute public static void RegisterRoutes(RouteCollection routes) { routes.Add(new Route("{resource}.axd/{*pathInfo}",new StopRoutingHandler())); OR routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); }
  • 148. MVC Nuget Packages Packages ELMAH.MVC PagedList.Mvc Glimpse.MVC5 WebBackgrounder Modernizr Lucene.NET Grid.Mvc AnglicanGeek.MarkdownMailer Bootstrap Helpers Persia