SlideShare ist ein Scribd-Unternehmen logo
1 von 266
October 2015
 MVC separates the user interface of an application into
three main aspects:
 The Model
 The View
 The Controler
 A set of classes that describes the data you’re working
with as well as the business rules for how the data can
be changed and manipulated
 Defines how the application’s UI will be displayed
 A set of classes that handles communication from the
user, overall application flow, and application-specific
logic.
 Models:
 Represent domain objects that encapsulate:
 data stored in a database
 code to manipulate the data
 code to enforce domain-specific business logic
 Example: encapsulating Entity Framework
 View:
 Template to dynamically generate HTML
 Controller:
 Class that manages the relationship between the View
and the Model
 It responds to user input, talks to the model, and
decides which view to render (if any).
 MVC is a pattern that can be applied to different
frameworks
 ASP.NET MVC
 The MVC pattern has been applied to ASP.NET. This
does not mean that it is the same as MVC running in
other places.
 10 months after MVC 2
 The Razor view engine
 Support for .NET 4 Data Annotations
 Improved model validation
 Greater control and flexibility with support for
dependency resolution and global action filters
 Better JavaScript support with unobtrusive JavaScript,
jQuery Validation, and JSON binding
 Use of NuGet to deliver software and manage
dependencies throughout the platform
 Code-focused templating for HTML generation
 Compact, expressive, and fluid
 Not a new language
 Easy to learn
 Works with any text editor
 IntelliSense
 No XML-like heavy syntax
 Features include:
 ASP.NET Web API
 Enhancements to the default project templates
 Mobile project template using jQuery Mobile
 Display Modes
 Task Support for Asynchronous Controllers
 Bundling and Minification
 Referred to as Web API
 A framework that offers the ASP.NET MVC
development style but is tailored to writing HTTP
services. (service-oriented design)
 Several MVC features have been adopted for HTTP
Service domain:
 Routing
 Model Binding and Validation
 Filters
 Scaffolding
 Easy Unit Testability
 Web API also adds a few new concepts and features to
the HTTP service development:
 HTTP programming model
 Action dispatching based on HTTP verbs
 Content negotiation
 Code-based configuration
 http://www.asp.net/mvc/mvc5
 A convention-based approach to allow selecting
different views based on the browser making the
request.
 Index.cshtml vs Index.Mobile.cshtml
 You can also register your own custom criteria.
 Index.WinPhone.cshtml
 Same as ASP.NET 4.5
 Works on scripts and CSS
 Minifies the request via several techniques
 Compresses the size of CSS via several techniques
 You can create custom bundles to contain specific
scripts and reference them with a single URL
 Json.NET
 Included in MVC 4 as a part of the Web API to support
serializing data to JSON format allowing for:
 Data contracts
 Anonoymous types
 Dynamic types
 Dates
 TimeSpans
 Object reference presevation
 Indenting
 Camel casing
 LINQ to JSON is also included along with automatic
conversion from JSON to XML
 DotNetOpenAuth:
 Used to support OpenID and Oauth-based logins
 Facebook
 Microsoft
 Google
 Twitter
 MVC 4 also provides an OAuthWebSecurity class
 AuthConfig.cs
 Used to configure security settings, including sites for
OAuth login.
 BundleConfig.cs
 Used to register bundles used by the bundling and
minification system. By default it inlcudes jQuery,
jQueryUI, jQuery valiation, Modernizr, and default CSS
references
 FilterConfig.cs:
 Used to register global MVC filters. By default the
HandlerErrorAttribute is registered. You can put other
filter registrations here.
 Filters:
 An action filter is an attribute that you can apply to a
controller action -- or an entire controller -- that
modifies the way in which the action is executed. The
ASP.NET MVC framework includes several action filters:
 OutputCache – This action filter caches the output of a
controller action for a specified amount of time.
 HandleError – This action filter handles errors raised when a
controller action executes.
 Authorize – This action filter enables you to restrict access to
a particular user or role.
 RouteConfig.cs
 Contains routing
 WebApiConfig.cs
 Used to register Web API routes, as well as set any
additional Web API configuration settings
 May 2012 the ASP.NET Web Stack open source
announcement marked the transition of ASP.NET
MVC, ASP.NET Web Pages, and ASP.NET Web API
from open source licensed code to fully open source
projects.
 All code changes and issue tracking for these projects
is done in public code repositories, and these projects
are allowed to accept community code contributions if
the team agrees that the changes make sense.
 http://aspnetwebstack.codeplex.com/SourceControl/li
st/changesets
 Visual Studio 2012 (included)
 Can be installed on:
 Visual Studio 2010 SP1
 Visual Web Developer 2010 Express SP1
 Can be installed side-by-side previous versions of MVC
 Internet Application:
 Contains the beginnings of an MVC web application,
including basic account management functions that use
ASP.NET Membership.
 Intranet Application:
 Added in ASP.NET MVC 3 tools update. Similar to the
Internet Application template, but the account management
functions use Windows accounts rather than ASP.NET
Membership.
 Basic Template:
 Minimal. Has basic folders, CSS, and MVC application
infrastructure in place, but no more. You need to do work in
order to get the application to run. For experienced MVC
developers that don’t want the predefined items in the
project.
 Empty:
 Only has the assemblies and the basic folder structure in
place
 Mobile Application:
 Preconfigured with jQuery Mobile.
 Includes mobile visual themes, a touch-optimized UI,
and support for Ajax navigation
 Web API template:
 Similar to the Internet Application template but is
streamlined for Web API development
 ASPX
 Razor
 Just check the box!
 You can add other Test Frameworks like NUnit,
MbUnit, or xUnit if you want to.
 http://msdn.microsoft.com/en-
us/library/dd381614.aspx
 Controllers – Controller classes that handle URL
request go here (MVC 4, controller classes can go
anywhere)
 Models – Classes that represent and manipulate data
and business objects go here
 Views – UI template files that are responsible for
rendering output go here
 Scripts – JavaScript files and scripts go here
 Images – images used on your site go here
 Content – CSS and other site content, other than
images and scripts, goes here
 Filters – Filter code goes here
 App_Data – Store data files that you read and write to,
here
 App_Start – Configuration code for features like
Routing, Bundling and Web API goes here
 ASP.NET MVC does not require this Directory
Structure.
 “Convention over configuration”
 ASP.NET MVC is heavily convention-based
 Uses Directory-naming structure when resolving view
templates.
 Allows you to omit the location path when referencing views
from within a Controller class.
 Each controller’s class name ends with Controller
 LegalController, LegalServicesController,
HomeController
 One Views directory for all the views of your
application
 Views that controllers use live in a subdirectory of the
Views main directory and are named according to the
controller name(minus the Controller suffix)
 Views for the LegalController would live in /Views/Legal
 Reusable UI elements live in a similar structure, but in
a Shared directory in the Views folder
 Model View Controller:
 1st Controller basics, then the other stuff.
 Have a look at the HomeController
 Responsible for deciding what will happen when you browse
to the homepage of the website.
 Responsible for responding to user input, making
changes to the model in response to user input if
needed.
 Controllers are concerned with the flow of the
application, working with data that comes in and
providing data going out to the relevant view.
 The URL tells the routing mechanism (later chapter)
which controller class to instantiate and which
action method to call, and supplies the required
arguments to that method.
 The controller’s method then decides which view to
use, and that view then renders the HTML.
 The controller’s method could return something
other than a view.
 There is a relationship between the URL and the
METHOD on a controller class. Not a relationship
between the URL and a FILE on the web server.
 MVC serves up the results of method calls, not
dynamically generated pages.
 (More about routing in later chapter)
 Add additional methods for additional scenarios.
 These methods are called Controller Actions or Action
Methods
 They respond to URL request, perform the appropriate
actions, and return a response back to the browser or user
that invoked the URL
• The Browse and Details methods to cover additional
scenarios.
 Browsing to /LegalServices/Browse caused the browse
method of the LegalServicesController to be executed.
 NO extra configuration was needed.
 This is routing in action. More later
 We created the controller class which was very simple.
 Inherits from System.Web.Mvc.Controller
 We returned text to the browser without a model or a
view.
 /LegalServices/Details/5 vs.
/LegalServices/Details?ID=5
 The default routing convention in MVC will
automatically pass the URL segment to you as a
parameter. The default parameter is named “ID”
 If your parameter is not “ID” then use the “?” or
configure routing.
 The previous example was not common and was
oversimplified.
 You will almost always use Views
 You will most often return ActionResult instead of
strings
 And routing is more complex that shown.
 Controllers orchestrate the interactions of the user, the
model objects and the views.
 They are responsible for:
 responding to the user input
 Manipulating the appropriate model objects
 And then selecting the appropriate view to display back
to the user in response to the initial input
 Before talking about Views, let’s look at ActionResults
 http://weblogs.asp.net/rajbk/archive/2010/05/03/actionresult-types-in-mvc2.aspx
 http://msdn.microsoft.com/en-
us/library/system.web.mvc.actionresult(v=vs.100).aspx
 The user’s first impression of your site starts with the
View
 Responsible for providing the user interface to the
user.
 The view transforms a model into a format ready to be
presented to the user.
 The view examines the model object and transforms
the contents to HTML
 Note:
 Not all views render HTML, but HTML is the most
common case
 More info on alternate types of content later.
 The Views directory contains a folder for your
controller, with the same name as the controller, but
without the controller suffix.
 [Take a look]
 HomeController has views in the Home directory
 Within the view folder (also called controller folder)
there’s a view file for each action method, named the
same as the action method.
 This is how views are associated to an action method.
 An action method can return a ViewResult via the
View() method.
 When the view name isn’t specified, the ViewResult
returned by the action method applies a convention to
locate the view.
 It first looks for a view with the same name as the action
within the /Views/ControllerName directory. “Ex:
/views/home/Index.cshtml”
 The View() method is overloaded. You can supply a view
name to render a different view. “ex: View(“MyView”)”
 It will still look in the same directory, but will look for the
“MyView.cshtml” file.
 View(“~/Views/DifferentDirectory/Index.cshtml”)
 To get to a different directory, provide the full path to that
directory. You must provide the file extension as well. This
bypasses the internal lookup mechanism.
 Passing information from the Controller to the View
 Data is passed from the controllers to the views via a ViewDataDictionary (a
specialized dictionary class) called ViewData.
 You can use standard dictionary syntax: ViewData[“CurrentTime”] =
DateTime.Now;
 ViewBag is a dynamic wrapper around ViewData
 The ViewBag leverages the C# 4 keyword “dynamic”
 The syntax is simplified:
 ViewBag.CurrentTime = DateTime.Now;
 Note:
 @Html.TextBox(“name”, ViewBag.Name) won’t compile because of the dynamic
type.
 Try:
 @Html.TextBox(“name”, (string)ViewBag.Name) or use ViewData[“Name”]
instead
 See page 51 Note
 Create a simple
View
 You can add a collection or list of items to the
ViewBag:
 Instead of adding a collection or
list of items to the ViewBag
and passing it to the view, and
then iterating through it in the
view, the ViewData object has a
Model property that can be set
by using the overload of the
View() method.
 To make it easier to deal with the class names you can
add a namespace by using the @using MyApp.Models
(foldername)
 Or if used frequently add the namespace to the
web.config
 There can be only one model in the ViewData.Model
object
 What happens if you need additional items that aren’t in
the Model object?
 You could add that data to the ViewBag and be done,
but not everyone likes this
 View Model
 A better name would be (View Specific Model)
 Not MVVM
 Used to display a variety of data that comes from
different places. Aggregating data into a single Model
that can be used by a view.
 Ex: Case Info, Lawyer Info, and User Info that needs to
be displayed by a single View
 You could also just add the info to a ViewBag and skip
creating a View Model
 It would work but it wouldn’t be strongly typed
 View Name
 View Engine
 Create a strongly-typed view
 Model Class
 Scaffold Template
 Reference Script Libraries
 Create a partial view
 Use a layout or master page
 ViewStart.cshtml
 Empty
 Creates an empty view. Only the model type is specified using the @model syntax
 Create
 Creates a view with a form for creating new instances of the model. Generates a label and input field for
each property of the model type
 Delete
 Creates a view with a form for deleting existing instances of the model. Displays a label and the current
value for each property of the model
 Details
 Creates a view that displays a label and the value for each property of the model type
 Edit
 Creates a view with a form for editing existing instances of the model. Generates a label and input field
for each property of the model type.
 List
 Creates a view with a table of model instances. Generates a column for each property of the model type.
Makes sure to pass an Ienumerable<yourModelType> to this view from your action method. The view
also contains links to actions for performing the create / edit / delete operations
 This option is used to indicate whether the view your are
creating should include references to a set of JavaScript
files if it makes sense for the view.
 By default, the _Layout.cshtml file references the main
jQuery library, but doesn’t reference the jQuery
Validation library or the Unobtrusive jQuery
Validation library.
 Check the box to reference these libraries when doing Edit
view, or Create view.
 A partial view is not a full view.
 The layout option will be disabled if you select this
option
 No <html> tag or <head> tag at the top of the view
 Determines whether or not the view you are creating
will reference a layout (or master page) or will be self-
contained.
 For Razor view engines, specifiying a layout is not
necessary if you choose to use the default layout
because the layout is already specified in the
_ViewStart.cshtml file.
 This option can be used to override the default Layout
file.
 What is Razor?
 Introduced in ASP.NET MVC 3 and is the default view
engine moving forward
 Provides a clean, lightweight, simple view engine.
 Provides a streamlined syntax for expressing views
 Minimizes the amount of syntax and extra characters.
 C# syntax has the .cshtml file extention
 VB - .vbhtml
 File Extension signals that the Razer parser should be
used
 Just type the @ symbol in the HTML and insert some code
 The @ symbol is used to transition from markup to code
and sometimes to transition back to markup
 @{}
 @(item).Models
 @@ to escape
 Use parenthesis whenever there is ambiguity
 Razor expressions are automatically HTML encoded.
 This is great for mitigating XSS
@{
string message = “<script>alert(‘hi there’);</script>”;
}
<span>@message</span>
This statement will not create an alert box
 You can use the HTML.Raw() method to return a
string that Razor will not encode.
 You can also create an instance of HTMLString
 Razor’s automatic HTML encoding is not sufficient for
displaying user input within JavaScript
 When setting variables in JavaScript to values supplied by
the user, it’s important to use JavaScript string encoding
and not just HTML encoding.
 http://localhost:49693/home/escript?name=Jonx3cscriptx3e%20alert(x27pwndx27)%20x3c/scriptx3e
 http://localhost:49693/home/escript?name=<script>alert('bob')</script>
 Ref: page 63
 @{}
 <Span>@Model.Message</span>
 Code expressions are evaluated and written to the
response.
 Code expressions are always HTML encoded
 <span>Product ID: @(PID)<span>
 <span>@Html.Raw(model.Message)</span>
@{
int x = 900;
string y = “bob is cool”;
}
 Blocks of code are simply sections of code that are
executed.
 Useful for declaring variables that you may need in
your code later
@foreach(var item in items){
<span>Item: @item.Name.</span>
}
@if(showMessage){
<text>This is plain text</text>
}
@if (showMessage){
this is plain text.
}
@* *@
@(Html.Amethod<TheType>())
Use parenthesis just like with explicit code expressions.
 Same purpose as MasterPages
 Maintain a consistent look and feel across multiple
views within your application
 Simpler syntax that MasterPages and greater
flexability
 Contains one or more placeholders that the other
views can provide content for.
 Looks like a standard Razor view, but has specific place
holders.
 @RenderBody
 Placeholder where views using this layout will have their
main content rendered.
 @RenderSection(“Footer”)
 @RenderSection(“Footer”, required:false)
@section Footer{
This is <i>footer</i> content!
}
@if(IsSectionDefined(“Footer”)){
RenderSection(“Footer”);
}
Else{
<span>Some default content</span>
}
Or use Templated Razor Delagates (Page 392 (Later))
 _ViewStart.cshtml
 Specifies the default layout
 Any view can override this layout and choose a different
one.
 Return a Partial View in the form of a
PartialViewResult via the PartialView() method.
 A Partial View does not specify a layout
 Useful in partial update scenarios using AJAX.
 An object that represents the data in the application.
 Often corresponds to tables in the database, but they
don’t have to.
 Controller action methods which return an
ActionResult can pass a model object to the view.
 You may need to figure out what the model should
represent or how it should be implemented. This may
be based on business requirements or conversations
with business owners or customers.
 What problem are you trying to solve?
 List? Edit? Create? Delete?
 Generates the boilerplate code you need for create, read,
update, and delete (CRUD) functionality in an application.
 Scaffolding templates can examine the type definition for a
model, then generate a controller and the controller’s
views.
 It knows how to name the controllers, how to name the
views, what code needs to go in each component, and
where to place all the pieces within the project.
 It takes care of the boring work
 Empty Controller
 Controller with Empty Read/Write actions
 API Controller with Empty Read/Write Actions
 Controller with Read/Write actions and Views, using
Entity Framework
 Class that derives from Controller
 Index is the only action in the controller, with not
code inside
 Adds a controller with Index, Details, Create, Edit, and
Delete
 You still need to add code to make it work
 Derived from ApiController base class.
 You can use this class to build a Web API for your
application
 Generates the controller with Index, Details, Create, Edit and
Delete actions
 Also Generates all the required views and code to persist and
retrieve information from a database.
 When you select the model class, the scaffolding examines all
the properties of your model and uses the info to build
controllers, views, and data access code.
 To generate the Data Access Code, the scaffolding also needs the
name of the DataContext object, if it exist. If not the scaffolding
can create one for you.
 Entity Framework (EF) is and object-relational
mapping framework.
 It understands how to store .NET objects in a
relational database and retrieve those same objects
given a LINQ query.
 EF supports a Code-First style of development
 Start storing and retrieving information in SQL server without creating
a database schema or opening a Visual Studio designer
 Write .NET classes and EF figures out how, and where, to store
instances of those classes.
 This is why your properties in your model object are virtual.
 Marking them as virtual, gives EF a hook into your classes and enables
features like an efficient change tracking mechanism.
 EF needs to know when a property value on a model changes, in case it
needs to update the datasource.
 Model-first
 Schema-first
 Both supported along with code-first
 If you have a class named Laywer, EF will create a table
named Laywers
 If you have a property named LawyerId, EF will
assume that it’s the Key value
 This too is by convention
 Derive from the DbContext class
 One or more properties of type DbSet<t>
 t is the type of object you want to persist
Public class LegalDB : DbContext
{
public DbSet<Laywer> Lawyers { get; set;}
public DbSet<Case> Cases { get; set;}
}
 The DbContext can be created manually or
automatically via the create controller dialog
 Change to Virtual Methods for EF
 Overview of LINQ
 Overview of Lamda
 Eager loading:
 var jails = db.Jails.Include(j => j.Cells);
 Brings all of the related objects on the first call
 Lazy Loading
 Brings all of the related objects when touched
 But this can cause a query for every item touched
 20 Jails with could cause 21 extra queries to the database
 Note: page 80
 The Scaffolding created views in the appropriate folder
 Index, edit, delete, details, create
 Examine the views that were created by the scaffolding
 Make changes
 In Code-first, EF attempts to use convention over
configuration as much as possible.
 If you don’t configure specific mappings from your
models to database tables and columns, EF uses
conventions to create a database schema.
 If you don’t configure a specific db connection to use at
runtime, EF creates on using a convention.
 To allow the EF to re-create an existing database:
 DropCreateDatabaseAlways
 DropCreateDatabaseIfModelChanges
System.Data.Entity.Database.SetInitializer(new
System.Data.Entity.DropCreateDatabaseIfModelChanges<JLegal.Models.JailDB3Context>());
 EF 4.3 includes the ability to discover the changes you’ve
made to the model objects and generate schema change
instructions for SQL Server.
 Migration allows you to preserve existing data in your
database as you build and refine your model definitions
 http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-
3-code-based-migrations-walkthrough.aspx
 http://msdn.microsoft.com/en-US/data/jj591621
 Derive from the DropCreateDatabaseAlways class and
override the Seed method.
 Use the new class in the SetInitializer
 Note: 84 -85
 In previous code:
 ModelState:
 The model knows if it is valid or not
 EntityState
 Next page
 db.SaveChanges
 RedirectToAction(“Index”)
 No more reading from the Request.Form Collection unless
you want to.
 Naming convention takes care of it all
 DefaultModelBinder
 Automatically converts the Form info to the Model object
based on naming convention.
 It uses the Request not just the Form Collection.
 It looks at route data, the querystring, and the Form
Collection and custom value providers if needed.
 Page 91
 You can have multiple model binders registered in the
MVC runtime for different types of models, but the
defaultModelBinder may work for you.
 The default uses naming conventions to find the matches.
 If it sees a FirstName property it looks for a FirstName
value in the request.
 It uses “value providers” to search for the values in different
parts of the request.
 Action tells the web browser where to send the
information
 Method
 Get
 Send info in the header
 Viewable in the Querystring
 Post
 Send info in the Body
 Not Viewable in the Querystring
 Html Helpers are methods you can invoke on the Html
property of a view.
 Url Helpers
 Also available from the controller
 Ajax Helpers
 Make views easy to author.
@using (Html.BeginForm(“Search”, “Home”,
FormMethod.Get))
 All helpers that output model values will automatically
HTML encode the values before rendering.
 System.Web.Mvc.HtmlHelper<t>
 Several items implemented as extension methods by
the framework
 System.Web.Mvc.Html Namespace
 Note:
 Views/web.config has the namespace entry
 Displays an unordered list of all validation errors in
the ModelState dictionary
 ModelState.AddModelError(“”, “wrong”);
 Model-level error (no key)
 ModelState.AddModelError(“Title”, “Bad Name);
 Property-Level (key provided)
 http://msdn.microsoft.com/en-us/library/dd410596(v=VS.98).aspx
 Difference between
 Html.Label
 Html.LabelFor
 Works with a model
 Not to be confused with the “for” attribute
 Templated helpers provide a way to automatically build UI based on a data
model that is marked with attributes defined in the
System.ComponentModel.DataAnnotations namespace.
 Templated Helpers
 Html.Display
 Html.Editor
 Strongly Typed Templated Helpers
 Html.DisplayFor
 Html.EditorFor
 Whole-Model Templated Helpers
 Html.DisplayForModel
 Html.EditorForModel
 Use Html.EditorFor to render the same HTML as
TextBoxFor, however, you can change the HTML using
data annotations.
 ModelState is a byproduct of model binding and holds all validation errors
detected during model building.
 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. If the value exists in the ModelState, the helper
uses the value from the ModelState instead of a value in the view data.
 User enters “Bob” into the Price fields and submits, when the view is returned
to the user because the model binding failed, the user will still see “Bob”
 When ModelState contains an error for a given property, the form helper
associated with the error renders a CSS class of input-validation-error (red)
 Html.ActionLink
 Html.RouteLink
 Action
 Exactly like ActionLink but does not return an anchor
 Content
 Can convert a relative application path to an absolute
application path
 RouteUrl
 Same pattern as Action, but accepts a route name like
RouteLink
 Html.Partial
 Renders partial view to a string.
 Html.RenderPartial
 Renders partial view to the response output stream
instead of returning a string.
 Action
 Executes a separate controller action and displays the
result
 RenderAction
 Writes directly to the response
 [ChildActionOnly]
 http://www.asp.net/mvc/tutorials/older-
versions/views/creating-custom-html-helpers-cs
 http://www.asp.net/mvc/tutorials/older-
versions/views/using-the-tagbuilder-class-to-build-
html-helpers-cs
 an unobtrusive validation library built on top of jquery.validation
 MVC comes with support for Data Annotations (that is,
System.ComponentModel.DataAnnotations) and can be extended
 becoming more popular and is being baked in to many other Microsoft
offerings, including Entity Framework
 MVC only contains four validators: Range, Required, StringLength and Regular
Expression
 The Data Annotations Extensions project can be found
at http://dataannotationsextensions.org/, and currently provides 11 additional
validation attributes (ex: Email, EqualTo, Min/Max) on top of Data
Annotations’ original 4.
 .NET 4.5 http://msdn.microsoft.com/en-
us/library/system.componentmodel.dataannotations(v=vs.110).aspx
 System.ComponentModel.DataAnnotations
namespace (some in other namespaces)
 Provide Server-side validation
 The framework also supports client-side validation
when you use one of the attributes on a model
property
 There are 4 attributes in this namespace
 Creates a required value
 Raises a validation error if the property value is null or
empty
 Client and server-side logic (although client-side validation
is actually through a validation adapter design)
 If the client does not have JavaScript enabled in the
browser, the validation logic will catch the it on the server,
too. The user will still see the error.
 [Phone]
 [EmailAddress]
 [CreditCard]
 System.Web.Mvc namespace
 By default, the MVC framework executes validation
logic during model binding.
 Part of a system of model binders, model metadata,
model validators and model state.
 The model binder runs implicitly when you have
parameters to an action method
 Once the model binder is finished updating the model
properties with new values, the model binder uses the
current model metadata and ultimately obtains all the
validators for the model.
 DataAnnotationsModelValidator
 A model validator that can find all the validation attributes
and execute the validation logic inside.
 The model binder catches all the failed validation rules
and places them into the Model State
 Model binding produces model state.
 Model state is accessible in a Controller-derived object
using the ModelState property
 Model state contains all the values the user attempted to
put into model properties
 Model state also contains all the errors associated with
each property, and errors associated with the model itself.
 If there is an error in model state Model.IsValid returns
false
 Many possibilities:
 Package validation logic into a custom data annotation
 Package validation logic into the model itself (self-
validating model)
 Derive from ValidationAttribute base class
 System.ComponentModel.DataAnnotations
namespace
 Override the IsValid method
 Add a constructor
 Pass the error message to the base class.
 Allow for custom error message
 Display a friendly name to the UI
 The default order is 10000
 Fields appear in ascending order
 http://msdn.microsoft.com/en-
us/library/hh390735.aspx
 [ForeignKeyAttribute]
 [TabletAttrubute]
 Threats:
 Cross-Site Scripting XSS
 Cross-Site Request Forgery
 Over-Posting
 Open Redirection
 Asynchronous JavaScript and XML
 The core of the support for Ajax in the ASP.NET MVC 4
framework comes from the jQuery JavaScript library
 jQuery is added to your project by the Template you
selected.
 Scripts folder
 Added by NuGet
 Can easily upgrade scripts when a new version of jQuery
arrives
 jQuery function (aliased as the $ sign)
 Less typing
 You can subscribe to events
 jQuery includes what you need to send asynchronous
request back to your server.
 You can generate Post or Get request and jQuery will
notify you when the request is complete (error or not)
 Consume XML, HTML, Text or JSON
 Keeping the JavaScript code separate from markup
 Create a .js file in the scripts folder
 Add a <script> tag to the view
 Must come later than the jQuery script tag
 Modernizes old browsers.
 Enables HTML 5 elements on browsers that don’t
support HTML 5
 Also detects other features like geolocation and the
drawing canvas if available.
 Add a reference to :
 A Razor view has an Ajax property available
 Data “dash” attributes
 Your MVC application needs at lease one route to
define how the app should handle request.
 You can have many routes in your application.
 Global.asax.cs
 RouteConfig.RegisterRoutes(RouteTable.Routes);
 App_Start folder:
 url segments
 A segment is everything between slashes but not
including the slashes
 Url Parameters
 Each contains a parameter in curly braces
 This is a pattern matching rule
 “{controller}/{action}/{id}”
 {controller} is used to instantiate a controller class to
handle the request. MVC appends the suffix “Controller”
to the value of the {controller} URL parameter and
attempts to find a type of that name.
 {action} is used to indicate which method of the controller
to call in order to handle the current request.
 {id} looks for a parameter named id
@Html.RouteLink("blog", new
{controller="Blog", action="Index“
, year=2341, month=23, day=34})
http://[domain name]/2012/02/24
 Allow you to divide your models, views, and controllers
into separate functional sections.
 Separate larger or complex sites into sections
 Each Area will have its own set of folders for controllers, views,
models
 Each area will have its own routing registration
 Derive a class from the AreaRegistration class
 Override AreaName and RegisterArea
 Demo:
 Create two Areas
 Each area has its own routing registration
 Routing is not looking for an exact match. Just a
sufficient match.
 Extra parameters will be placed in the querystring
prameters (after the ?)
 LESS: http://designshack.net/articles/css/10-less-css-
examples-you-should-steal-for-your-projects/
 http://lesscss.org/
 HTTP services on top of the .NET framework
 Ships with MVC 4
 Why?
 Reach more clients
 Xml, json,
 Scale with the cloud
 Embrace HTTP
 Simplify communication with clients
 A software design pattern
 Types of Patterns in use today
 Inversion of Control
 Service Locator
 Weakly Typed Service Locator
 Strongly Typed Service Locator
 Dependency Injection
 Constructor Injection
 Property Injection
 Coupling / Tightly Coupling
 When a component has a dependency.
 Ex: creating an instance of class “A” within the constructor class “B”
 Class “B” can’t work if class “A” (the dependency) isn’t available.
 Your class knows exactly what kind of class it needs to use.
 Makes it hard or impossible to use a different type of the same class.
 Changes to the class “A” may break class “B”
 What if you wanted to use class “C” instead of class “A”?
 Moving the responsibility for creating the instance of
the class (Class A) outside of the class (Class B) that
consumes the dependency
 2 steps:
 Create a layer of abstraction
 Interface
 Move the responsibility for creating the instance outside
of the consuming class
 Pass the class via the constructor or a property
 Or use a Service locator
 An external component that finds the service (class)
that you are looking for. Your class relies on the
locator to always give it back the correct type. Your
class doesn’t care what type it is because it expects a
type that has implemented the correct interface.
 Good for unit testing
 Similar to the Strongly typed service locator but
returns object instead of a specific interface
 Your class must cast to the correct type of interface
 You could create a Generic Type as well
 This pattern is a type of Inversion of Control
 No service locator
 Good for testing
 Constructor Injection:
 Pass the dependency into the constructor
 Property Injection:
 Pass the dependency into a property
 Acts as a factory for components, inspecting and
fulfilling their dependency requirements
 A little different than a service locator
 Service locator:
 If anyone asks for this type, give them this object
 DIC:
 If anyone asks for this type, you create an object of this
concrete type and give them that

Weitere ähnliche Inhalte

Was ist angesagt?

ASP .NET MVC Introduction & Guidelines
ASP .NET MVC Introduction & Guidelines  ASP .NET MVC Introduction & Guidelines
ASP .NET MVC Introduction & Guidelines Dev Raj Gautam
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC PresentationVolkan Uzun
 
ASP .NET MVC
ASP .NET MVC ASP .NET MVC
ASP .NET MVC eldorina
 
Mvc pattern and implementation in java fair
Mvc   pattern   and implementation   in   java fairMvc   pattern   and implementation   in   java fair
Mvc pattern and implementation in java fairTech_MX
 
Just a View: An Introduction To Model-View-Controller Pattern
Just a View:  An Introduction To Model-View-Controller PatternJust a View:  An Introduction To Model-View-Controller Pattern
Just a View: An Introduction To Model-View-Controller PatternAaron Nordyke
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)M Ahsan Khan
 
MVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,MobileMVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,Mobilenaral
 
MVC Seminar Presantation
MVC Seminar PresantationMVC Seminar Presantation
MVC Seminar PresantationAbhishek Yadav
 
MVC Architecture in ASP.Net By Nyros Developer
MVC Architecture in ASP.Net By Nyros DeveloperMVC Architecture in ASP.Net By Nyros Developer
MVC Architecture in ASP.Net By Nyros DeveloperNyros Technologies
 
PHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterPHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterKHALID C
 

Was ist angesagt? (19)

ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
ASP .NET MVC Introduction & Guidelines
ASP .NET MVC Introduction & Guidelines  ASP .NET MVC Introduction & Guidelines
ASP .NET MVC Introduction & Guidelines
 
Session 1
Session 1Session 1
Session 1
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
ASP .NET MVC
ASP .NET MVC ASP .NET MVC
ASP .NET MVC
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Mvc pattern and implementation in java fair
Mvc   pattern   and implementation   in   java fairMvc   pattern   and implementation   in   java fair
Mvc pattern and implementation in java fair
 
Mvc4
Mvc4Mvc4
Mvc4
 
MVC Framework
MVC FrameworkMVC Framework
MVC Framework
 
MSDN - ASP.NET MVC
MSDN - ASP.NET MVCMSDN - ASP.NET MVC
MSDN - ASP.NET MVC
 
Just a View: An Introduction To Model-View-Controller Pattern
Just a View:  An Introduction To Model-View-Controller PatternJust a View:  An Introduction To Model-View-Controller Pattern
Just a View: An Introduction To Model-View-Controller Pattern
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
What is MVC?
What is MVC?What is MVC?
What is MVC?
 
MVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,MobileMVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,Mobile
 
MVC Seminar Presantation
MVC Seminar PresantationMVC Seminar Presantation
MVC Seminar Presantation
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
MVC Architecture in ASP.Net By Nyros Developer
MVC Architecture in ASP.Net By Nyros DeveloperMVC Architecture in ASP.Net By Nyros Developer
MVC Architecture in ASP.Net By Nyros Developer
 
PHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterPHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniter
 

Andere mochten auch

Fundamentosdejava herbertschildt-121220095835-phpapp02
Fundamentosdejava herbertschildt-121220095835-phpapp02Fundamentosdejava herbertschildt-121220095835-phpapp02
Fundamentosdejava herbertschildt-121220095835-phpapp02david hincapie
 
Abuhail Social Club PPT
Abuhail Social Club PPTAbuhail Social Club PPT
Abuhail Social Club PPTIllyas Ibrahim
 
Eclipse luna roja
Eclipse luna rojaEclipse luna roja
Eclipse luna rojaPeriodico12
 
Maintaining Systems Resilience through the winter in Eastern Cheshire
Maintaining Systems Resilience through the winter in Eastern CheshireMaintaining Systems Resilience through the winter in Eastern Cheshire
Maintaining Systems Resilience through the winter in Eastern CheshireMatthew Cunningham
 
Human Resource Management
Human Resource ManagementHuman Resource Management
Human Resource Managementkajal Sankhe
 
Kill bill research analysis
Kill bill research analysisKill bill research analysis
Kill bill research analysisimogen3
 
Produccion y producctividad
Produccion y producctividadProduccion y producctividad
Produccion y producctividaddeilysmar malave
 
GBAF242 ECT Underlying Financial Position
GBAF242 ECT Underlying Financial PositionGBAF242 ECT Underlying Financial Position
GBAF242 ECT Underlying Financial PositionMatthew Cunningham
 
Investigacion
Investigacion Investigacion
Investigacion chelsey98
 
A8hcqdusfighmnagsobw signature-c86a07381c552e271ea067ec05fb574d1661495ea080c4...
A8hcqdusfighmnagsobw signature-c86a07381c552e271ea067ec05fb574d1661495ea080c4...A8hcqdusfighmnagsobw signature-c86a07381c552e271ea067ec05fb574d1661495ea080c4...
A8hcqdusfighmnagsobw signature-c86a07381c552e271ea067ec05fb574d1661495ea080c4...Kedir Bade
 
Game Sense Presentation
Game Sense PresentationGame Sense Presentation
Game Sense Presentationejcoggo
 

Andere mochten auch (20)

Tema 4 naturales
Tema 4 naturalesTema 4 naturales
Tema 4 naturales
 
nafeel(1)
nafeel(1)nafeel(1)
nafeel(1)
 
Fundamentosdejava herbertschildt-121220095835-phpapp02
Fundamentosdejava herbertschildt-121220095835-phpapp02Fundamentosdejava herbertschildt-121220095835-phpapp02
Fundamentosdejava herbertschildt-121220095835-phpapp02
 
Digital
DigitalDigital
Digital
 
Gorgona islandpres
Gorgona islandpresGorgona islandpres
Gorgona islandpres
 
Abuhail Social Club PPT
Abuhail Social Club PPTAbuhail Social Club PPT
Abuhail Social Club PPT
 
Eclipse luna roja
Eclipse luna rojaEclipse luna roja
Eclipse luna roja
 
Maintaining Systems Resilience through the winter in Eastern Cheshire
Maintaining Systems Resilience through the winter in Eastern CheshireMaintaining Systems Resilience through the winter in Eastern Cheshire
Maintaining Systems Resilience through the winter in Eastern Cheshire
 
Patent Copy
Patent CopyPatent Copy
Patent Copy
 
SAFe in 8 Pictures
SAFe in 8 PicturesSAFe in 8 Pictures
SAFe in 8 Pictures
 
Human Resource Management
Human Resource ManagementHuman Resource Management
Human Resource Management
 
Kill bill research analysis
Kill bill research analysisKill bill research analysis
Kill bill research analysis
 
CAB.PPTX
CAB.PPTXCAB.PPTX
CAB.PPTX
 
Produccion y producctividad
Produccion y producctividadProduccion y producctividad
Produccion y producctividad
 
GBAF242 ECT Underlying Financial Position
GBAF242 ECT Underlying Financial PositionGBAF242 ECT Underlying Financial Position
GBAF242 ECT Underlying Financial Position
 
Investigacion
Investigacion Investigacion
Investigacion
 
A8hcqdusfighmnagsobw signature-c86a07381c552e271ea067ec05fb574d1661495ea080c4...
A8hcqdusfighmnagsobw signature-c86a07381c552e271ea067ec05fb574d1661495ea080c4...A8hcqdusfighmnagsobw signature-c86a07381c552e271ea067ec05fb574d1661495ea080c4...
A8hcqdusfighmnagsobw signature-c86a07381c552e271ea067ec05fb574d1661495ea080c4...
 
BIMTECH Information Bulletin - 2017
BIMTECH Information Bulletin - 2017BIMTECH Information Bulletin - 2017
BIMTECH Information Bulletin - 2017
 
Game Sense Presentation
Game Sense PresentationGame Sense Presentation
Game Sense Presentation
 
Tema 3 el sociales
Tema 3 el socialesTema 3 el sociales
Tema 3 el sociales
 

Ähnlich wie MVC Separates User Interface into Models, Views, Controllers

Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanGigin Krishnan
 
Asp 1-mvc introduction
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introductionFajar Baskoro
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To MvcVolkan Uzun
 
Introduction to ASP.NET MVC 1.0
Introduction to ASP.NET MVC 1.0Introduction to ASP.NET MVC 1.0
Introduction to ASP.NET MVC 1.0Shiju Varghese
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamentalldcphuc
 
Asp.net With mvc handson
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handsonPrashant Kumar
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101Rich Helton
 
ASP.Net | Sabin Saleem
ASP.Net | Sabin SaleemASP.Net | Sabin Saleem
ASP.Net | Sabin SaleemSaBin SaleEm
 
Technoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development servicesTechnoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development servicesAaron Jacobson
 
Introduction to ASP.NET Core MVC and the MVC Pattern.pptx
Introduction to ASP.NET Core MVC and the MVC Pattern.pptxIntroduction to ASP.NET Core MVC and the MVC Pattern.pptx
Introduction to ASP.NET Core MVC and the MVC Pattern.pptxQuickwayInfoSystems3
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarAppfinz Technologies
 
Ppt of Basic MVC Structure
Ppt of Basic MVC StructurePpt of Basic MVC Structure
Ppt of Basic MVC StructureDipika Wadhvani
 

Ähnlich wie MVC Separates User Interface into Models, Views, Controllers (20)

Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
 
Asp 1-mvc introduction
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introduction
 
Mvc Brief Overview
Mvc Brief OverviewMvc Brief Overview
Mvc Brief Overview
 
Mvc
MvcMvc
Mvc
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
 
Introduction to ASP.NET MVC 1.0
Introduction to ASP.NET MVC 1.0Introduction to ASP.NET MVC 1.0
Introduction to ASP.NET MVC 1.0
 
Asp.net,mvc
Asp.net,mvcAsp.net,mvc
Asp.net,mvc
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamental
 
Asp.net With mvc handson
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handson
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
 
ASP.Net | Sabin Saleem
ASP.Net | Sabin SaleemASP.Net | Sabin Saleem
ASP.Net | Sabin Saleem
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
Technoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development servicesTechnoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development services
 
Introduction to ASP.NET Core MVC and the MVC Pattern.pptx
Introduction to ASP.NET Core MVC and the MVC Pattern.pptxIntroduction to ASP.NET Core MVC and the MVC Pattern.pptx
Introduction to ASP.NET Core MVC and the MVC Pattern.pptx
 
Mvc
MvcMvc
Mvc
 
MVC - Introduction
MVC - IntroductionMVC - Introduction
MVC - Introduction
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumar
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Ppt of Basic MVC Structure
Ppt of Basic MVC StructurePpt of Basic MVC Structure
Ppt of Basic MVC Structure
 

Kürzlich hochgeladen

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
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
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
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
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
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

Kürzlich hochgeladen (20)

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 ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
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
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
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 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
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
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

MVC Separates User Interface into Models, Views, Controllers

  • 2.  MVC separates the user interface of an application into three main aspects:  The Model  The View  The Controler
  • 3.  A set of classes that describes the data you’re working with as well as the business rules for how the data can be changed and manipulated
  • 4.  Defines how the application’s UI will be displayed
  • 5.  A set of classes that handles communication from the user, overall application flow, and application-specific logic.
  • 6.  Models:  Represent domain objects that encapsulate:  data stored in a database  code to manipulate the data  code to enforce domain-specific business logic  Example: encapsulating Entity Framework
  • 7.  View:  Template to dynamically generate HTML  Controller:  Class that manages the relationship between the View and the Model  It responds to user input, talks to the model, and decides which view to render (if any).
  • 8.
  • 9.  MVC is a pattern that can be applied to different frameworks  ASP.NET MVC  The MVC pattern has been applied to ASP.NET. This does not mean that it is the same as MVC running in other places.
  • 10.  10 months after MVC 2  The Razor view engine  Support for .NET 4 Data Annotations  Improved model validation  Greater control and flexibility with support for dependency resolution and global action filters  Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding  Use of NuGet to deliver software and manage dependencies throughout the platform
  • 11.  Code-focused templating for HTML generation  Compact, expressive, and fluid  Not a new language  Easy to learn  Works with any text editor  IntelliSense  No XML-like heavy syntax
  • 12.
  • 13.
  • 14.  Features include:  ASP.NET Web API  Enhancements to the default project templates  Mobile project template using jQuery Mobile  Display Modes  Task Support for Asynchronous Controllers  Bundling and Minification
  • 15.  Referred to as Web API  A framework that offers the ASP.NET MVC development style but is tailored to writing HTTP services. (service-oriented design)  Several MVC features have been adopted for HTTP Service domain:  Routing  Model Binding and Validation  Filters  Scaffolding  Easy Unit Testability
  • 16.  Web API also adds a few new concepts and features to the HTTP service development:  HTTP programming model  Action dispatching based on HTTP verbs  Content negotiation  Code-based configuration
  • 18.
  • 19.
  • 20.  A convention-based approach to allow selecting different views based on the browser making the request.  Index.cshtml vs Index.Mobile.cshtml  You can also register your own custom criteria.  Index.WinPhone.cshtml
  • 21.  Same as ASP.NET 4.5  Works on scripts and CSS  Minifies the request via several techniques  Compresses the size of CSS via several techniques  You can create custom bundles to contain specific scripts and reference them with a single URL
  • 22.
  • 23.  Json.NET  Included in MVC 4 as a part of the Web API to support serializing data to JSON format allowing for:  Data contracts  Anonoymous types  Dynamic types  Dates  TimeSpans  Object reference presevation  Indenting  Camel casing  LINQ to JSON is also included along with automatic conversion from JSON to XML
  • 24.  DotNetOpenAuth:  Used to support OpenID and Oauth-based logins  Facebook  Microsoft  Google  Twitter  MVC 4 also provides an OAuthWebSecurity class
  • 25.
  • 26.  AuthConfig.cs  Used to configure security settings, including sites for OAuth login.  BundleConfig.cs  Used to register bundles used by the bundling and minification system. By default it inlcudes jQuery, jQueryUI, jQuery valiation, Modernizr, and default CSS references  FilterConfig.cs:  Used to register global MVC filters. By default the HandlerErrorAttribute is registered. You can put other filter registrations here.
  • 27.  Filters:  An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters:  OutputCache – This action filter caches the output of a controller action for a specified amount of time.  HandleError – This action filter handles errors raised when a controller action executes.  Authorize – This action filter enables you to restrict access to a particular user or role.
  • 28.  RouteConfig.cs  Contains routing  WebApiConfig.cs  Used to register Web API routes, as well as set any additional Web API configuration settings
  • 29.  May 2012 the ASP.NET Web Stack open source announcement marked the transition of ASP.NET MVC, ASP.NET Web Pages, and ASP.NET Web API from open source licensed code to fully open source projects.  All code changes and issue tracking for these projects is done in public code repositories, and these projects are allowed to accept community code contributions if the team agrees that the changes make sense.  http://aspnetwebstack.codeplex.com/SourceControl/li st/changesets
  • 30.  Visual Studio 2012 (included)  Can be installed on:  Visual Studio 2010 SP1  Visual Web Developer 2010 Express SP1  Can be installed side-by-side previous versions of MVC
  • 31.
  • 32.  Internet Application:  Contains the beginnings of an MVC web application, including basic account management functions that use ASP.NET Membership.  Intranet Application:  Added in ASP.NET MVC 3 tools update. Similar to the Internet Application template, but the account management functions use Windows accounts rather than ASP.NET Membership.  Basic Template:  Minimal. Has basic folders, CSS, and MVC application infrastructure in place, but no more. You need to do work in order to get the application to run. For experienced MVC developers that don’t want the predefined items in the project.
  • 33.  Empty:  Only has the assemblies and the basic folder structure in place  Mobile Application:  Preconfigured with jQuery Mobile.  Includes mobile visual themes, a touch-optimized UI, and support for Ajax navigation  Web API template:  Similar to the Internet Application template but is streamlined for Web API development
  • 35.  Just check the box!  You can add other Test Frameworks like NUnit, MbUnit, or xUnit if you want to.  http://msdn.microsoft.com/en- us/library/dd381614.aspx
  • 36.  Controllers – Controller classes that handle URL request go here (MVC 4, controller classes can go anywhere)  Models – Classes that represent and manipulate data and business objects go here  Views – UI template files that are responsible for rendering output go here  Scripts – JavaScript files and scripts go here  Images – images used on your site go here
  • 37.  Content – CSS and other site content, other than images and scripts, goes here  Filters – Filter code goes here  App_Data – Store data files that you read and write to, here  App_Start – Configuration code for features like Routing, Bundling and Web API goes here
  • 38.  ASP.NET MVC does not require this Directory Structure.
  • 39.  “Convention over configuration”  ASP.NET MVC is heavily convention-based  Uses Directory-naming structure when resolving view templates.  Allows you to omit the location path when referencing views from within a Controller class.
  • 40.  Each controller’s class name ends with Controller  LegalController, LegalServicesController, HomeController  One Views directory for all the views of your application  Views that controllers use live in a subdirectory of the Views main directory and are named according to the controller name(minus the Controller suffix)  Views for the LegalController would live in /Views/Legal  Reusable UI elements live in a similar structure, but in a Shared directory in the Views folder
  • 41.
  • 42.  Model View Controller:  1st Controller basics, then the other stuff.  Have a look at the HomeController  Responsible for deciding what will happen when you browse to the homepage of the website.
  • 43.  Responsible for responding to user input, making changes to the model in response to user input if needed.  Controllers are concerned with the flow of the application, working with data that comes in and providing data going out to the relevant view.
  • 44.  The URL tells the routing mechanism (later chapter) which controller class to instantiate and which action method to call, and supplies the required arguments to that method.  The controller’s method then decides which view to use, and that view then renders the HTML.  The controller’s method could return something other than a view.
  • 45.  There is a relationship between the URL and the METHOD on a controller class. Not a relationship between the URL and a FILE on the web server.  MVC serves up the results of method calls, not dynamically generated pages.  (More about routing in later chapter)
  • 46.
  • 47.
  • 48.
  • 49.  Add additional methods for additional scenarios.  These methods are called Controller Actions or Action Methods  They respond to URL request, perform the appropriate actions, and return a response back to the browser or user that invoked the URL
  • 50.
  • 51. • The Browse and Details methods to cover additional scenarios.
  • 52.  Browsing to /LegalServices/Browse caused the browse method of the LegalServicesController to be executed.  NO extra configuration was needed.  This is routing in action. More later  We created the controller class which was very simple.  Inherits from System.Web.Mvc.Controller  We returned text to the browser without a model or a view.
  • 53.  /LegalServices/Details/5 vs. /LegalServices/Details?ID=5  The default routing convention in MVC will automatically pass the URL segment to you as a parameter. The default parameter is named “ID”  If your parameter is not “ID” then use the “?” or configure routing.
  • 54.  The previous example was not common and was oversimplified.  You will almost always use Views  You will most often return ActionResult instead of strings  And routing is more complex that shown.
  • 55.  Controllers orchestrate the interactions of the user, the model objects and the views.  They are responsible for:  responding to the user input  Manipulating the appropriate model objects  And then selecting the appropriate view to display back to the user in response to the initial input
  • 56.  Before talking about Views, let’s look at ActionResults  http://weblogs.asp.net/rajbk/archive/2010/05/03/actionresult-types-in-mvc2.aspx  http://msdn.microsoft.com/en- us/library/system.web.mvc.actionresult(v=vs.100).aspx
  • 57.
  • 58.
  • 59.  The user’s first impression of your site starts with the View  Responsible for providing the user interface to the user.  The view transforms a model into a format ready to be presented to the user.  The view examines the model object and transforms the contents to HTML
  • 60.  Note:  Not all views render HTML, but HTML is the most common case  More info on alternate types of content later.
  • 61.
  • 62.  The Views directory contains a folder for your controller, with the same name as the controller, but without the controller suffix.  [Take a look]  HomeController has views in the Home directory  Within the view folder (also called controller folder) there’s a view file for each action method, named the same as the action method.  This is how views are associated to an action method.  An action method can return a ViewResult via the View() method.
  • 63.  When the view name isn’t specified, the ViewResult returned by the action method applies a convention to locate the view.  It first looks for a view with the same name as the action within the /Views/ControllerName directory. “Ex: /views/home/Index.cshtml”  The View() method is overloaded. You can supply a view name to render a different view. “ex: View(“MyView”)”  It will still look in the same directory, but will look for the “MyView.cshtml” file.  View(“~/Views/DifferentDirectory/Index.cshtml”)  To get to a different directory, provide the full path to that directory. You must provide the file extension as well. This bypasses the internal lookup mechanism.
  • 64.  Passing information from the Controller to the View  Data is passed from the controllers to the views via a ViewDataDictionary (a specialized dictionary class) called ViewData.  You can use standard dictionary syntax: ViewData[“CurrentTime”] = DateTime.Now;  ViewBag is a dynamic wrapper around ViewData  The ViewBag leverages the C# 4 keyword “dynamic”  The syntax is simplified:  ViewBag.CurrentTime = DateTime.Now;  Note:  @Html.TextBox(“name”, ViewBag.Name) won’t compile because of the dynamic type.  Try:  @Html.TextBox(“name”, (string)ViewBag.Name) or use ViewData[“Name”] instead  See page 51 Note
  • 65.  Create a simple View
  • 66.  You can add a collection or list of items to the ViewBag:
  • 67.  Instead of adding a collection or list of items to the ViewBag and passing it to the view, and then iterating through it in the view, the ViewData object has a Model property that can be set by using the overload of the View() method.
  • 68.
  • 69.  To make it easier to deal with the class names you can add a namespace by using the @using MyApp.Models (foldername)  Or if used frequently add the namespace to the web.config
  • 70.  There can be only one model in the ViewData.Model object  What happens if you need additional items that aren’t in the Model object?  You could add that data to the ViewBag and be done, but not everyone likes this
  • 71.  View Model  A better name would be (View Specific Model)  Not MVVM  Used to display a variety of data that comes from different places. Aggregating data into a single Model that can be used by a view.  Ex: Case Info, Lawyer Info, and User Info that needs to be displayed by a single View  You could also just add the info to a ViewBag and skip creating a View Model  It would work but it wouldn’t be strongly typed
  • 72.
  • 73.  View Name  View Engine  Create a strongly-typed view  Model Class  Scaffold Template  Reference Script Libraries  Create a partial view  Use a layout or master page  ViewStart.cshtml
  • 74.  Empty  Creates an empty view. Only the model type is specified using the @model syntax  Create  Creates a view with a form for creating new instances of the model. Generates a label and input field for each property of the model type  Delete  Creates a view with a form for deleting existing instances of the model. Displays a label and the current value for each property of the model  Details  Creates a view that displays a label and the value for each property of the model type  Edit  Creates a view with a form for editing existing instances of the model. Generates a label and input field for each property of the model type.  List  Creates a view with a table of model instances. Generates a column for each property of the model type. Makes sure to pass an Ienumerable<yourModelType> to this view from your action method. The view also contains links to actions for performing the create / edit / delete operations
  • 75.  This option is used to indicate whether the view your are creating should include references to a set of JavaScript files if it makes sense for the view.  By default, the _Layout.cshtml file references the main jQuery library, but doesn’t reference the jQuery Validation library or the Unobtrusive jQuery Validation library.  Check the box to reference these libraries when doing Edit view, or Create view.
  • 76.  A partial view is not a full view.  The layout option will be disabled if you select this option  No <html> tag or <head> tag at the top of the view
  • 77.  Determines whether or not the view you are creating will reference a layout (or master page) or will be self- contained.  For Razor view engines, specifiying a layout is not necessary if you choose to use the default layout because the layout is already specified in the _ViewStart.cshtml file.  This option can be used to override the default Layout file.
  • 78.  What is Razor?  Introduced in ASP.NET MVC 3 and is the default view engine moving forward  Provides a clean, lightweight, simple view engine.  Provides a streamlined syntax for expressing views  Minimizes the amount of syntax and extra characters.
  • 79.
  • 80.  C# syntax has the .cshtml file extention  VB - .vbhtml  File Extension signals that the Razer parser should be used
  • 81.  Just type the @ symbol in the HTML and insert some code  The @ symbol is used to transition from markup to code and sometimes to transition back to markup  @{}  @(item).Models  @@ to escape  Use parenthesis whenever there is ambiguity
  • 82.  Razor expressions are automatically HTML encoded.  This is great for mitigating XSS @{ string message = “<script>alert(‘hi there’);</script>”; } <span>@message</span> This statement will not create an alert box
  • 83.  You can use the HTML.Raw() method to return a string that Razor will not encode.  You can also create an instance of HTMLString
  • 84.
  • 85.  Razor’s automatic HTML encoding is not sufficient for displaying user input within JavaScript  When setting variables in JavaScript to values supplied by the user, it’s important to use JavaScript string encoding and not just HTML encoding.  http://localhost:49693/home/escript?name=Jonx3cscriptx3e%20alert(x27pwndx27)%20x3c/scriptx3e  http://localhost:49693/home/escript?name=<script>alert('bob')</script>
  • 86.  Ref: page 63  @{}
  • 87.  <Span>@Model.Message</span>  Code expressions are evaluated and written to the response.  Code expressions are always HTML encoded
  • 88.  <span>Product ID: @(PID)<span>
  • 90. @{ int x = 900; string y = “bob is cool”; }  Blocks of code are simply sections of code that are executed.  Useful for declaring variables that you may need in your code later
  • 91. @foreach(var item in items){ <span>Item: @item.Name.</span> }
  • 92. @if(showMessage){ <text>This is plain text</text> } @if (showMessage){ this is plain text. }
  • 93. @* *@
  • 94. @(Html.Amethod<TheType>()) Use parenthesis just like with explicit code expressions.
  • 95.  Same purpose as MasterPages  Maintain a consistent look and feel across multiple views within your application  Simpler syntax that MasterPages and greater flexability  Contains one or more placeholders that the other views can provide content for.
  • 96.
  • 97.  Looks like a standard Razor view, but has specific place holders.  @RenderBody  Placeholder where views using this layout will have their main content rendered.
  • 98.  @RenderSection(“Footer”)  @RenderSection(“Footer”, required:false) @section Footer{ This is <i>footer</i> content! } @if(IsSectionDefined(“Footer”)){ RenderSection(“Footer”); } Else{ <span>Some default content</span> } Or use Templated Razor Delagates (Page 392 (Later))
  • 99.  _ViewStart.cshtml  Specifies the default layout  Any view can override this layout and choose a different one.
  • 100.  Return a Partial View in the form of a PartialViewResult via the PartialView() method.  A Partial View does not specify a layout  Useful in partial update scenarios using AJAX.
  • 101.
  • 102.  An object that represents the data in the application.  Often corresponds to tables in the database, but they don’t have to.  Controller action methods which return an ActionResult can pass a model object to the view.
  • 103.  You may need to figure out what the model should represent or how it should be implemented. This may be based on business requirements or conversations with business owners or customers.  What problem are you trying to solve?  List? Edit? Create? Delete?
  • 104.  Generates the boilerplate code you need for create, read, update, and delete (CRUD) functionality in an application.  Scaffolding templates can examine the type definition for a model, then generate a controller and the controller’s views.  It knows how to name the controllers, how to name the views, what code needs to go in each component, and where to place all the pieces within the project.  It takes care of the boring work
  • 105.  Empty Controller  Controller with Empty Read/Write actions  API Controller with Empty Read/Write Actions  Controller with Read/Write actions and Views, using Entity Framework
  • 106.  Class that derives from Controller  Index is the only action in the controller, with not code inside
  • 107.  Adds a controller with Index, Details, Create, Edit, and Delete  You still need to add code to make it work
  • 108.  Derived from ApiController base class.  You can use this class to build a Web API for your application
  • 109.  Generates the controller with Index, Details, Create, Edit and Delete actions  Also Generates all the required views and code to persist and retrieve information from a database.  When you select the model class, the scaffolding examines all the properties of your model and uses the info to build controllers, views, and data access code.  To generate the Data Access Code, the scaffolding also needs the name of the DataContext object, if it exist. If not the scaffolding can create one for you.
  • 110.  Entity Framework (EF) is and object-relational mapping framework.  It understands how to store .NET objects in a relational database and retrieve those same objects given a LINQ query.
  • 111.  EF supports a Code-First style of development  Start storing and retrieving information in SQL server without creating a database schema or opening a Visual Studio designer  Write .NET classes and EF figures out how, and where, to store instances of those classes.  This is why your properties in your model object are virtual.  Marking them as virtual, gives EF a hook into your classes and enables features like an efficient change tracking mechanism.  EF needs to know when a property value on a model changes, in case it needs to update the datasource.
  • 112.  Model-first  Schema-first  Both supported along with code-first
  • 113.  If you have a class named Laywer, EF will create a table named Laywers  If you have a property named LawyerId, EF will assume that it’s the Key value  This too is by convention
  • 114.  Derive from the DbContext class  One or more properties of type DbSet<t>  t is the type of object you want to persist Public class LegalDB : DbContext { public DbSet<Laywer> Lawyers { get; set;} public DbSet<Case> Cases { get; set;} }
  • 115.  The DbContext can be created manually or automatically via the create controller dialog
  • 116.  Change to Virtual Methods for EF
  • 117.  Overview of LINQ  Overview of Lamda
  • 118.  Eager loading:  var jails = db.Jails.Include(j => j.Cells);  Brings all of the related objects on the first call  Lazy Loading  Brings all of the related objects when touched  But this can cause a query for every item touched  20 Jails with could cause 21 extra queries to the database  Note: page 80
  • 119.  The Scaffolding created views in the appropriate folder  Index, edit, delete, details, create
  • 120.  Examine the views that were created by the scaffolding  Make changes
  • 121.  In Code-first, EF attempts to use convention over configuration as much as possible.  If you don’t configure specific mappings from your models to database tables and columns, EF uses conventions to create a database schema.  If you don’t configure a specific db connection to use at runtime, EF creates on using a convention.
  • 122.  To allow the EF to re-create an existing database:  DropCreateDatabaseAlways  DropCreateDatabaseIfModelChanges System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<JLegal.Models.JailDB3Context>());
  • 123.  EF 4.3 includes the ability to discover the changes you’ve made to the model objects and generate schema change instructions for SQL Server.  Migration allows you to preserve existing data in your database as you build and refine your model definitions  http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4- 3-code-based-migrations-walkthrough.aspx  http://msdn.microsoft.com/en-US/data/jj591621
  • 124.  Derive from the DropCreateDatabaseAlways class and override the Seed method.  Use the new class in the SetInitializer  Note: 84 -85
  • 125.
  • 126.
  • 127.
  • 128.  In previous code:  ModelState:  The model knows if it is valid or not  EntityState  Next page  db.SaveChanges  RedirectToAction(“Index”)
  • 129.
  • 130.  No more reading from the Request.Form Collection unless you want to.  Naming convention takes care of it all  DefaultModelBinder  Automatically converts the Form info to the Model object based on naming convention.  It uses the Request not just the Form Collection.  It looks at route data, the querystring, and the Form Collection and custom value providers if needed.  Page 91
  • 131.
  • 132.  You can have multiple model binders registered in the MVC runtime for different types of models, but the defaultModelBinder may work for you.  The default uses naming conventions to find the matches.  If it sees a FirstName property it looks for a FirstName value in the request.  It uses “value providers” to search for the values in different parts of the request.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.  Action tells the web browser where to send the information  Method  Get  Send info in the header  Viewable in the Querystring  Post  Send info in the Body  Not Viewable in the Querystring
  • 138.  Html Helpers are methods you can invoke on the Html property of a view.  Url Helpers  Also available from the controller  Ajax Helpers  Make views easy to author. @using (Html.BeginForm(“Search”, “Home”, FormMethod.Get))
  • 139.
  • 140.  All helpers that output model values will automatically HTML encode the values before rendering.
  • 141.
  • 142.  System.Web.Mvc.HtmlHelper<t>  Several items implemented as extension methods by the framework  System.Web.Mvc.Html Namespace  Note:  Views/web.config has the namespace entry
  • 143.  Displays an unordered list of all validation errors in the ModelState dictionary
  • 144.  ModelState.AddModelError(“”, “wrong”);  Model-level error (no key)  ModelState.AddModelError(“Title”, “Bad Name);  Property-Level (key provided)
  • 145.
  • 147.
  • 148.
  • 149.
  • 150.  Difference between  Html.Label  Html.LabelFor  Works with a model  Not to be confused with the “for” attribute
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.  Templated helpers provide a way to automatically build UI based on a data model that is marked with attributes defined in the System.ComponentModel.DataAnnotations namespace.  Templated Helpers  Html.Display  Html.Editor  Strongly Typed Templated Helpers  Html.DisplayFor  Html.EditorFor  Whole-Model Templated Helpers  Html.DisplayForModel  Html.EditorForModel
  • 160.  Use Html.EditorFor to render the same HTML as TextBoxFor, however, you can change the HTML using data annotations.
  • 161.  ModelState is a byproduct of model binding and holds all validation errors detected during model building.  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. If the value exists in the ModelState, the helper uses the value from the ModelState instead of a value in the view data.  User enters “Bob” into the Price fields and submits, when the view is returned to the user because the model binding failed, the user will still see “Bob”  When ModelState contains an error for a given property, the form helper associated with the error renders a CSS class of input-validation-error (red)
  • 162.
  • 163.
  • 164.
  • 165.
  • 167.  Action  Exactly like ActionLink but does not return an anchor  Content  Can convert a relative application path to an absolute application path  RouteUrl  Same pattern as Action, but accepts a route name like RouteLink
  • 168.  Html.Partial  Renders partial view to a string.  Html.RenderPartial  Renders partial view to the response output stream instead of returning a string.
  • 169.  Action  Executes a separate controller action and displays the result  RenderAction  Writes directly to the response  [ChildActionOnly]
  • 170.
  • 173.
  • 174.
  • 175.  an unobtrusive validation library built on top of jquery.validation  MVC comes with support for Data Annotations (that is, System.ComponentModel.DataAnnotations) and can be extended  becoming more popular and is being baked in to many other Microsoft offerings, including Entity Framework  MVC only contains four validators: Range, Required, StringLength and Regular Expression  The Data Annotations Extensions project can be found at http://dataannotationsextensions.org/, and currently provides 11 additional validation attributes (ex: Email, EqualTo, Min/Max) on top of Data Annotations’ original 4.  .NET 4.5 http://msdn.microsoft.com/en- us/library/system.componentmodel.dataannotations(v=vs.110).aspx
  • 176.
  • 177.  System.ComponentModel.DataAnnotations namespace (some in other namespaces)  Provide Server-side validation  The framework also supports client-side validation when you use one of the attributes on a model property  There are 4 attributes in this namespace
  • 178.  Creates a required value  Raises a validation error if the property value is null or empty  Client and server-side logic (although client-side validation is actually through a validation adapter design)  If the client does not have JavaScript enabled in the browser, the validation logic will catch the it on the server, too. The user will still see the error.
  • 179.
  • 181.
  • 183.
  • 184.
  • 185.  By default, the MVC framework executes validation logic during model binding.  Part of a system of model binders, model metadata, model validators and model state.  The model binder runs implicitly when you have parameters to an action method
  • 186.
  • 187.  Once the model binder is finished updating the model properties with new values, the model binder uses the current model metadata and ultimately obtains all the validators for the model.  DataAnnotationsModelValidator  A model validator that can find all the validation attributes and execute the validation logic inside.  The model binder catches all the failed validation rules and places them into the Model State
  • 188.  Model binding produces model state.  Model state is accessible in a Controller-derived object using the ModelState property  Model state contains all the values the user attempted to put into model properties  Model state also contains all the errors associated with each property, and errors associated with the model itself.  If there is an error in model state Model.IsValid returns false
  • 189.
  • 190.
  • 191.
  • 192.  Many possibilities:  Package validation logic into a custom data annotation  Package validation logic into the model itself (self- validating model)
  • 193.  Derive from ValidationAttribute base class  System.ComponentModel.DataAnnotations namespace
  • 194.  Override the IsValid method  Add a constructor
  • 195.  Pass the error message to the base class.
  • 196.  Allow for custom error message
  • 197.
  • 198.
  • 199.
  • 200.  Display a friendly name to the UI
  • 201.  The default order is 10000  Fields appear in ascending order
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 209.
  • 210.  Threats:  Cross-Site Scripting XSS  Cross-Site Request Forgery  Over-Posting  Open Redirection
  • 211.  Asynchronous JavaScript and XML  The core of the support for Ajax in the ASP.NET MVC 4 framework comes from the jQuery JavaScript library
  • 212.  jQuery is added to your project by the Template you selected.  Scripts folder  Added by NuGet  Can easily upgrade scripts when a new version of jQuery arrives
  • 213.  jQuery function (aliased as the $ sign)  Less typing
  • 214.
  • 215.  You can subscribe to events
  • 216.
  • 217.
  • 218.  jQuery includes what you need to send asynchronous request back to your server.  You can generate Post or Get request and jQuery will notify you when the request is complete (error or not)  Consume XML, HTML, Text or JSON
  • 219.  Keeping the JavaScript code separate from markup
  • 220.
  • 221.  Create a .js file in the scripts folder  Add a <script> tag to the view  Must come later than the jQuery script tag
  • 222.  Modernizes old browsers.  Enables HTML 5 elements on browsers that don’t support HTML 5  Also detects other features like geolocation and the drawing canvas if available.
  • 223.  Add a reference to :
  • 224.  A Razor view has an Ajax property available
  • 225.  Data “dash” attributes
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
  • 233.
  • 234.
  • 235.
  • 236.  Your MVC application needs at lease one route to define how the app should handle request.  You can have many routes in your application.
  • 238.  url segments  A segment is everything between slashes but not including the slashes  Url Parameters  Each contains a parameter in curly braces  This is a pattern matching rule
  • 239.  “{controller}/{action}/{id}”  {controller} is used to instantiate a controller class to handle the request. MVC appends the suffix “Controller” to the value of the {controller} URL parameter and attempts to find a type of that name.  {action} is used to indicate which method of the controller to call in order to handle the current request.  {id} looks for a parameter named id
  • 240.
  • 241.
  • 242. @Html.RouteLink("blog", new {controller="Blog", action="Index“ , year=2341, month=23, day=34}) http://[domain name]/2012/02/24
  • 243.  Allow you to divide your models, views, and controllers into separate functional sections.  Separate larger or complex sites into sections  Each Area will have its own set of folders for controllers, views, models  Each area will have its own routing registration  Derive a class from the AreaRegistration class  Override AreaName and RegisterArea
  • 244.  Demo:  Create two Areas
  • 245.  Each area has its own routing registration
  • 246.
  • 247.
  • 248.
  • 249.
  • 250.
  • 251.
  • 252.
  • 253.  Routing is not looking for an exact match. Just a sufficient match.  Extra parameters will be placed in the querystring prameters (after the ?)
  • 254.
  • 256.
  • 257.  HTTP services on top of the .NET framework  Ships with MVC 4  Why?  Reach more clients  Xml, json,  Scale with the cloud  Embrace HTTP  Simplify communication with clients
  • 258.
  • 259.
  • 260.  A software design pattern  Types of Patterns in use today  Inversion of Control  Service Locator  Weakly Typed Service Locator  Strongly Typed Service Locator  Dependency Injection  Constructor Injection  Property Injection
  • 261.  Coupling / Tightly Coupling  When a component has a dependency.  Ex: creating an instance of class “A” within the constructor class “B”  Class “B” can’t work if class “A” (the dependency) isn’t available.  Your class knows exactly what kind of class it needs to use.  Makes it hard or impossible to use a different type of the same class.  Changes to the class “A” may break class “B”  What if you wanted to use class “C” instead of class “A”?
  • 262.  Moving the responsibility for creating the instance of the class (Class A) outside of the class (Class B) that consumes the dependency  2 steps:  Create a layer of abstraction  Interface  Move the responsibility for creating the instance outside of the consuming class  Pass the class via the constructor or a property  Or use a Service locator
  • 263.  An external component that finds the service (class) that you are looking for. Your class relies on the locator to always give it back the correct type. Your class doesn’t care what type it is because it expects a type that has implemented the correct interface.  Good for unit testing
  • 264.  Similar to the Strongly typed service locator but returns object instead of a specific interface  Your class must cast to the correct type of interface  You could create a Generic Type as well
  • 265.  This pattern is a type of Inversion of Control  No service locator  Good for testing  Constructor Injection:  Pass the dependency into the constructor  Property Injection:  Pass the dependency into a property
  • 266.  Acts as a factory for components, inspecting and fulfilling their dependency requirements  A little different than a service locator  Service locator:  If anyone asks for this type, give them this object  DIC:  If anyone asks for this type, you create an object of this concrete type and give them that