Introduction to MVC
Lesson 4 - Controllers
[WHAT]
- ] VIDEO SUMMARY - notes on this lesson which explains what controllers do in more detail, covers adding controller Action methods, the various return types, looks at model binding, its pro's and con's and ...., using filters to add code prior to or after Action method execution, using vanity urls and MVC routing and some controller best practices that you want to adhere to.
[WHY]
- ] controller's - understanding
- ] controllers - action methods - adding
- ] HTTP GET, HTTP POST, -
- ] model binding -
- ] bind attribute
- ?] viewModel, ] custom binding
- ] filters
- ] vanity urls
- ] routing
[WHERE]
- ] WATCH THE FULL VIDEO
-
[WHEN]
- ] 2014-06-24 - produced
[EXAMPLE]
- [00:00] answering incoming chat questions
- ] monitors they are using - planar sc###
- ] source is up on github.com/jongalloway/MVA-introduction-to-aspnet-MVC
- ] how to use browserlink - multiple browsers, OPTION on use standard toolbar, can now launch your code in multiple browsers
- ] getting visual studio - download link - 2 options, free version OR trial verson of full product (
- ] for more advanced examples - see the
- ] codelens feature - really cool -
- ] c# course for absolute beginners - for those new to c#
- ] VS has git integration - they are using it to push code up to github
- ] more on "code first" integreation, search on msdn, article
- [06:30] until now magic, but its time to dig deeper and figure out whats happening, under the hood
- ] lots of functionality you can get with VS right out of the box, right click and go ....
- ] at some point, you will need to tweak your programs
- ] adding more advanced functionality
- ] all this will be done using actions and controllers
- [00:00] we will be taking control of our controllers ....
- ] ADD brand new action
- ] model binding
- ] filters
- ] vanity urls + routing
- ] controller best practices
- [09:00] adding Actions to controllers
- ] remember a model is just a class
- ] and a controller is a class
- ] we are adding a method to our class,
- [10:00] Action Signature & HTTP GET/POST in MVC vs FORMS
- ] Return type - ActionResult - FileResult, -JsonResult, -ViewResult
- ] Parameters - normal parameters, MVC model binding
- ] params are just like normal params,
- ] return types, FileResult, inheirits form ActionResult,
- ] viewResult, sends back a view, most common type you will be using
- ] HTTP GET gets info, HTTP POST typically send info up to the server
- ] create/update/delete are typically 2 step operations , ] create/present the form ] accept the data
- ] create 2 actions, - form presentation via http get, accept data via http post
- ] explains difference between web forms execution in a percievde single step VS asp.net MVC 2 step process
- [17:00] example - albums controller -
- ] currently has 2 methods, generated by scaffolding code, Index, Details
- ] FYI the design being used is NOT the way to go for a real world enterprise application, db code is in the controller ..
- ] public ActionResult Create()
- ] return View
- ] this is get by default, display's the form to the user
- ] [HTTPPOST] //ATTRIBUTES
- ] [VALIDATEANTIFORGERYTOKEN]
- ] public ActionResult Create(Album album)
- ] if modelState.IsValid(){
- ] db.Albums.Add(album)
- ] db.saveChanges()
- ] return RedirectToAction("Index")
- ] }
- ] return view(album)
- [19:30] example - displayByArtist
- ] public ActionResult displayByArtist(int ArtistID) (){
- ] return View();
- ] }
- ] View() is a helper method, Controller has many built in helper methods, functions, View is one of them
- ] View looks for the name of the view and for the DATA that the view needs
- ] diagrams - MVC workflow side by side with code ( SEE Photo tab above)
- ] // gets the data for a view from the db
- ] var albums = db.Albums.ToList()
- ] // sends the data(model) along to the view
- ] return View(albums);
- [23:30] model binding
- ] it just works - uses the name attribute of input elements,
- ] automatically matches parameter names for simple data types,
- ] complex objects are mapped by property name, complex properties use dotted notation, ex Album.LinerNotes
- ] in MVC everything is customizable, BUT just because you can customize something, it doesnt mean that you should
- ] customization, can mean - you are taking on more work, you then you need to
- [30:00] model binding pitfalls -
- ] can be exploited
- ] examples - users make yourself an admin, set the price of items to your price
- ] INCREDIBLY IMPORTANT - you want to control model binding
- [31:30] solutions - controlling whats being passed into the model binder
- ] simplest way - use the bind attribute
- ] Edit ([Bind(Include = "Song", "Title", "Length")] Song song)
- ] + - no other changes that you need to mak
- ] - - when you add another property to your "Song" class, you need to go back and edit the "Bind list" to include the new song property
- ] create a custom model binder - you can,
- ] but noooooooo, it can lead to another set of pitfalls
- ] create a view model
- ] ??
- [33:30] demo - bind attribute
- x] adds new property numOfSongs to class album
- x] builds project and shows that the Edit method, Bind attribute has not changed, still only includes orig 2 attributes
- >] VS TIP - CTRL+K + CTRL+C - will comment out a block of code
- >] VS TIP - CTRL+K + CTRL+U - will UN comment out a block of code
- ] ASIDE - change Create to ( FormCollection ) from: (Album), use DEBUG to illustrate ???
- [40:00] filters
- ] making our controllers dumb, only need to know the bare minimum, get some data, pass that data into the view
- ] sometimes more processing is required - example - allow editing for only users who created the album
- ] dont want to add this code into every single action
- ] add them to filters
- ] filters are attributes
- ] the goal is to alter the execution of the Action
- ] the MVC framework has a whole bunch of built in filters
- ] example compare adding security to web forms app
- ] with asp.net forms, you use web config file to specify file, files are always the same
- ] as long as we keep the attribute on top of it
- ] illustration 1 - code execution without filters
- ] illustration 2 - with filters
- ] filters add some Action pre execution code AND some Action post execution code
- [44:00] filters - adding
- ] Action
- ] Controller,
- ] Global, FilterConfig.cs - class you
- [44:30] Security Filters
- ] Authorize - control who can access a controller action
- ] Properties - Users, Roles
- ] ValidateAntiForgeryToken - defends against cross site request forgery, requires anti-forgery token to be added to view
- ] RequireHTTPS - requires SSL
- [45:30] about SSL
- ] authenticates server, ] encrypts traffic (prevents tampering),
- ] WHEN - ] asking for sensitive info (email, login, ...) ] after authentication
- ] enable SSL - why = reference article * irony - not https
- ] COSTs - ] certificate, not that expensive ] performance impact
- [47:00] filters - demo
- ] adding filter [Authorize()] to controller action ""
- ] attribute can be added to controller "action" method or to entire controller ( granular control)
- ] just adding the Authorize() filter, automatically redirects to "log in " page b/c
- [49:00] urls and vanity urls
- ] example url - http://mymusicstore.com/App/Album/Details/Display.aspx?id=42&bandID=21&...
- ] users dont know what it refers to , search engines dont know what it refers to, its ugly
- ] example vanity url - http://mymusicstore.com/Album/Cure/Disintegration
- ] you know what it refers to by looking at/reading it, search engines too,
- [50:30] MVC routing
- ] vanity urls are handled by routing
- ] routing in MVC controls what controller action is called based upon the URL provided
- ] methods for updating routing - ] routeConfig.cs ] Attribute Routing
- [51:30] DEMO - MVC routing - routeConfig.cs
- ] inside /App_Start directory, you will find RouteConfig.cs -- ?? -- can use this, but dont
- [52:00] DEMO - MVC routing - attribute routing
- ] [Route("/Album/Edit/{id:int}")]
- ] public ActionResult Edit(int id);
- ] calls the Edit action, in the Album controller, passes in the id value of album (if an int is passed in)
- [53:30] route prefix
- ] change the name of the route
- ] example you want to use "Album" vs "Albums" for your url,
- ] ADD [RoutePrefix("Album")] Attribute to Albums controller
- ] ....
- ] easy to setup, dont go nuts with it at first
- [57:30] controller design guidelines
- ] high cohesion - make sure all actions are closely related
- ] low/loose coupling - controllers should know as little as possible about the rest of the system
- ] repository pattern - wrap data calls into another object
- ] simplifies testing and changes
- ] REMEMBER - controller is a class and an action is a method, thats it, 90% of the battle
- ] controllers actions should be max 5 -10 lines of code, Dino Esposito - 1 line, methods should NOT be scrollabe, horizontal or vertical
- ] next lesson is on views
[HOW-TO]
- ] # 5050 - my project - guide to asp.net - MVC
- ] # # -
[REFERENCE]
- ] # 5359 - overview series - reference section, to-do, done
- ] status = 46% completed pre quiz, quiz results = 4/5, status = 55%
quiz
Which types of objects do actions return? Choose all that apply.
- view, files, json
You need to use a form to display data for a user and then accept any modifications to the data. Which two steps should you take?
- use GET to display form
- use POST to accept updated data
You can use Git from a command prompt or from the Visual Studio user interface.
T
You need to configure Visual Studio to display an application in multiple browsers. Which toolbar should you use?
- standard
x] Which statement about CodeLens is true?
- magnifies code in VS
? c = counts the number of references to ...
results =