Chengyu Sun California State University, Los Angeles

Slides:



Advertisements
Similar presentations
INTRODUCTION TO ASP.NET MVC AND EXAMPLE WALKTHROUGH RAJAT ARYA EFECS - OIM DAWG – 4/21/2009 ASP.NET MVC.
Advertisements

Introduction to MVC Adding a View Page NTPCUG Tom Perkins, Ph.D.
Introduction to MVC Action Methods, Edit View, and a Search Feature NTPCUG Dr. Tom Perkins.
DT211/3 Internet Application Development
06 | Implementing Web APIs Jon Galloway | Tech Evangelist Christopher Harrison | Head Geek.
Virtual techdays INDIA │ November 2010 ASP.Net MVC Deep Dive Sundararajan S │ Associate Tech Architect, Aditi Technologies.
Ori Calvo, 2010 “If people want to have maximum reach across *all* devices then HTML will provide the broadest reach” Scott Guthrie,
NextGen Technology upgrade – Synerizip - Sandeep Kamble.
Building Data Driven Applications Using WinRT and XAML Sergey Barskiy, Magenic Microsoft MVP – Data Platform Principal Consultant Level: Intermediate.
ASP.NET Web API Udaiappa Ramachandran NHDN-Nashua.NET/Cloud Computing UG Lead Blog:
Standalone Java Application vs. Java Web Application
Introduction to ASP.NET MVC Information for this presentation was taken from Pluralsight Building Applications with ASP.NET MVC 4.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Murach’s ASP.NET 4.0/VB, C1© 2006, Mike Murach & Associates, Inc.Slide 1.
Chapter 6 Server-side Programming: Java Servlets
Getting started with ASP.NET MVC Dhananjay
06 | HTTP Services with Web API Bruno Terkaly | Technical Evangelist Bret Stateham | Technical Evangelist.
RESTful Web Services What is RESTful?
Working with Data Model Binders, Display Templates, Editor Templates, Validation… SoftUni Team Technical Trainers Software University
Virtual techdays INDIA │ 9-11 February 2011 SESSION TITLE Kamala Rajan S │ Technical Manager, Marlabs.
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC -
BIT 286: Web Applications ASP.Net MVC. Objectives Applied MVC overview Controllers Intro to Routing Views ‘Convention over configuration’ Layout files.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
1 Using MVC 6. MVC vs. ASP Web Forms Both run under ASP.NET Can coexist In Web Forms, browser requests page. xxx.aspx and xxx.aspx.cs on the server Page.
Introduction to MVC Slavomír Moroz. Revision from Previous Lesson o ASP.NET WebForms applications Abstract away HTTP (similar to desktop app development)
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
Jim Fawcett CSE686 – Internet Programming Summer 2010
Jim Fawcett CSE686 – Internet Programming Spring 2014
ASP.NET Essentials SoftUni Team ASP.NET MVC Introduction
Introduction to .NET Florin Olariu
Asp.Net MVC Conventions
An introduction to ASP.Net with MVC Nischal S
Building production ready APIs with ASP.NET Core 2.0
Building Web Applications with Microsoft ASP
Jim Fawcett CSE686 – Internet Programming Spring 2012
Social Media And Global Computing Introduction to The MVC Pattern
Node.js Express Web Applications
Routing, Controllers, Actions, Views
CS5220 Advanced Topics in Web Programming JavaScript and jQuery
Play Framework: Introduction
Node.js Express Web Services
J2EE Lecture 7: Spring – Spring MVC
PHP Training at GoLogica in Bangalore
Anatomy of an ASP.NET Page
Controllers.
CS5220 Advanced Topics in Web Programming Spring – Web MVC
MIS Professor Sandvig MIS 324 Professor Sandvig
CS5220 Advanced Topics in Web Programming Angular – Routing
Data Structures and Database Applications View and Session Data
CS2011 Introduction to Programming I Objects and Classes
CS5220 Advanced Topics in Web Programming Spring – Web MVC
CS2011 Introduction to Programming I Methods (I)
Chengyu Sun California State University, Los Angeles
CS5220 Advanced Topics in Web Programming Angular – Routing
Building production-ready APIs with ASP.NET Core 2.2
CS4961 Software Design Laboratory Understand Aquila Backend
Rules and Tips for Good Web Programming (and Programming in General)
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
CS3220 Web and Internet Programming About Data Models
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
CS4540 Special Topics in Web Development Course Overview
CS4540 Special Topics in Web Development SQL and MS SQL
MIS Professor Sandvig MIS 324 Professor Sandvig
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Chengyu Sun California State University, Los Angeles CS4540 Special Topics in Web Development ASP.NET Core: Handling Requests with Controllers Chengyu Sun California State University, Los Angeles

Controllers in ASP.NET Core MVC Any class that meets at least one of the two conditions: Have a name ending in Controller Inherit from ControllerBase or Controller class Usually placed in the Controllers folder but can be anywhere in the project

A Controller Example public class EmployeesController : Controller { public IActionResult List() var employees = employeeService.GetEmployees(); return View( employees ); }

What Does An Action Method Return? An action method can return a view (or part of a view), which renders a response (or part of a response) An action method can also return a response, which can be a redirect, error, file, JSON, and so on IActionResult is the interface for all the possible return values of an action method

A Quick Look at the ControllerBase Class The base class for Controller Properties for accessing various data related to a request Helper methods for creating various responses, e.g. Ok, NotFound, File, Redirect Usually used as the base class for web API controllers

A Quick Look at the Controller Class Inherits from ControllerBase Adds support for views Type Name Usage Property ViewBag, ViewData For passing additional data to views TempData Single-use session data (usually used for redirect) Method View, PartialView, ViewComponent, Json For creating ViewResult or JsonResult OnActionExecuted, OnActionExecuting, OnActionExecutionAsync, Dispose Controller life cycle hooks

ViewData ViewData is a Dictionary<string,object> In controller: ViewData["employees"] = employees; Require casting In view: @foreach (var employee in (List<Employee>) ViewData["employees"]) { <tr> <td>@employee.Id</td><td>@employee.Name</td> </tr> }

ViewBag ViewBag is an ExpandoObject (i.e. expandable object) Supports dynamic properties whose types are determined at runtime, i.e. no casting necessary A wrapper of ViewData Example: ViewBag.employees = employees;

View Model vs. ViewData vs. ViewBag Type declared in view using @model Type can be determined at compilation time, thus allows code suggestion/completion in IDEs ViewData Dictionary<string,object> Require casting from object to the real type of the data ViewBag ExpandoObject Property types are determined at runtime – no casting required Why do we have ViewData when ViewBag seems better??

Example: View an Employee Route: "{controller=Home}/{action=Index}/{id?}" URL: Employees / View / 1 EmployeesController: IActionResult View( int id )

Routing in ASP.NET Core Map URLs of requests to controller actions Conventional routing is based on routes specified for the MVC middleware (i.e. each route establishes a convention) Attribute routing specifies mapping on a controller or action method, e.g. [Route("Employees/List")] public IActionResult List() { … }

A Route in Conventional Routing routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); A route in conventional routing must have a controller and an action

Route Template Route parameters "{controller=Home} / {action=Index} / {id?}" No leading / Route parameters must be separated by literal values controller and action are reserved names Default value and optional parameter

Example: View Two Employees Use URL like /Employees/Two/1/2 Use URL like /Employees/Two/1-2 Routes order is important – router will try each route in order and stop at the first match

Example: Wiki URLs Use a catch-all route parameter, e.g. "wiki/{*path}" or "wiki/{**path}" There's no difference between * and ** when using the parameter in an action method

Attribute Routing Examples [Route("Home/About")] public IActionResult About() { … } [Route("Help")] [Route("Home/About")] public IActionResult About() { … } [HttpGet] [Route("Employees/View/{id}")] public IActionResult View(int id) { … } [HttpGet("Employees/View/{id}")] public IActionResult View(int id) { … }

Route Constraints Route constraints can be used to restrict how the route parameters are match, e.g. [Route("users/{id:int}")] public User GetUserById(int id) { ... } [Route("users/{name}")] public User GetUserByName(string name) { ... }

Mixed Routing A web application can use both conventional and attribute routing Attribute routing takes precedence

Example: Add an Employee Routing based on HTTP request methods Binding Simple type Complex type RedirectToAction() More refactoring-friendly Easier to specify route parameters

Binding Map the data in a request to the parameters of an action method Request Add( string name, DateTime dateHired ) Add( Employee employee )

Binding Sources Route parameters Query parameters Request body Posted form fields Uploaded files Objects (e.g. JSON or XML) Request headers Defaults

Choosing Binding Source Using Attribute [FromRoute] [FromQuery] [FromForm] [FromBody] [FromHeader]

Binding Collections List<int> numbers numbers=100&numbers=200 Dictionary<string,string> courses courses[4022]=Databases& courses[4050]=DotnetCore courses[0].Key=4022&courses[0].Value=Databases& courses[1].Key=4050&courses[1].Value=DotnetCore

Models in MVC Controller Database View MVC Application HTTP request Domain Model Binding Model View Model Database HTTP response View MVC Application

About Model Class It's convenient to use the same model class for the different models, but some sometimes it may be necessary to create separate classes, e.g. to prevent over-posting attack

Readings ASP.NET Core in Action: Chapter 4, 5, 6 Routing in ASP.NET Core Model Binding in ASP.NET Core