Summary

This presentation introduces ASP.NET MVC, a web development framework. It covers topics such as MVC architecture, model binding, and exception handling. This will help beginners learn the core concepts of how to develop web applications using this framework.

Full Transcript

ASP.NET MVC Deloitte Tech Academy (DTA) Agenda Topics Description Concept, Solution Structure, HTML Helper, Razor view engine, Razor syntax, Action Result,...

ASP.NET MVC Deloitte Tech Academy (DTA) Agenda Topics Description Concept, Solution Structure, HTML Helper, Razor view engine, Razor syntax, Action Result, ASP.NET MVC Layout view, Partial View, Model, Routing concept, Routing config, Routing pattern, and MVC Area State Management Hidden Fields, Cookies, ViewBag, ViewData, and TempData Model Binding Model Binding, Bind Attributes, Filters, and Exception Handling 2 Copyright © 2023 Deloitte Development LLC. All rights reserved. Learning Objectives By the end of this session, you will be able to: Discuss the ASP.NET MVC framework Describe the concept of state management Identify the state management options available in ASP.NET MVC 3 Copyright © 2023 Deloitte Development LLC. All rights reserved. ASP.NET MVC Model View Controller (MVC) ASP.NET Model View Controller (MVC) is a web framework based on the MVC architecture. Developers can build dynamic web applications using the ASP.NET MVC framework that enables a clean separation of concerns, fast development, and is Test-Driven Development (TDD) friendly. 5 Copyright © 2023 Deloitte Development LLC. All rights reserved. Concept MVC divides web applications into three components—Model, View, and Controller. A view in MVC is a user interface and displays the model data to the user and enables them to modify them. A view in ASP.NET MVC can be HTML, View CSS, and some special syntax (Razor syntax) that simplifies communication with the model and the controller. The controller manages the user request. Usually, the user uses the view and raises an HTTP request, A model represents the shape which is handled by the of the data, and a class in C# controller. The controller Controller Model is used to describe a model. Manipulate The model objects store data processes the request and returns an appropriate view retrieved from the database. as a response. 6 Copyright © 2023 Deloitte Development LLC. All rights reserved. Solution Folder Structure App_Data Web.config App_Start Packages. Content config Solution Folder Global.asax Structure Controllers Views Fonts Scripts Models 7 Copyright © 2023 Deloitte Development LLC. All rights reserved. Solution Folder Structure (Cont.) Solution Folder Descriptions Structure Contains application data files like LocalDB,.mdf files, xml files, App_Data and other data-related files, but Internet Information Services (IIS) never serve files from the App_Data folder Contains class files, which is executed when the application starts; App_Start these are typically configuration files, such as AuthConfig.cs, BundleConfig.cs, FilterConfig.cs, and RouteConfig.cs Contains static files, such as CSS files, images, and icons files. By Content deault, the MVC application includes bootstrap.css, bootstrap.min.css, and Site.css. Contains class files for the controllers. Controllers handle users' Controllers requests and return a response, and MVC requires the name of all the controller files to end with "Controller" Fonts Contains custom font files for your application Contains model class files; the model class generally includes Models public properties that is used by the application to hold and manipulate application data 8 Copyright © 2023 Deloitte Development LLC. All rights reserved. Solution Folder Structure (Cont.) Solution Folder Descriptions Structure Contains JavaScript or VBScript files for the application, and MVC Scripts includes a few javascript files for bootstrap, jquery 1.10, and modernizer by default Contains html files for the application, and the view file is typically Views a.cshtml file, where you write html, C#, or VB.NET code Contains code that runs in response to application-level events, Global.asax such as application_BeginRequest, application_start, application_error, session_start, session_end Is handled by NuGet to keep track of the packages/versions Packages.config installed in solution Web.config Contains application-level configuration 9 Copyright © 2023 Deloitte Development LLC. All rights reserved. The HtmlHelper Class Creates HTML elements using the model class object in the @model razor view IEnumerable Connects the model object to HTML elements to display the @{ value of model properties into HTML elements and assigns the ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; value of the HTML elements to the model properties while } submitting the web form Index Is recommended to always use HtmlHelper class in the razor view instead of writing HTML tags manually @Html.ActionLink("Create New", "Create") Generates HTML elements No of students Enrolled View Bag: @Html is an object of HtmlHelper class. (@ symbol is used to @ViewBag.StudentCount access the server-side object in razor syntax). HTML is a No of students Enrolled View Data property of type HtmlHelper, which is included in the base class :@ViewData["StudentsCount"] of razor view WebViewPage. ActionLink() and DisplayNameFor() are the extension methods included in the HtmlHelper class. @Html.DisplayNameFor(model => model.StudentName) Example: @Html.ActionLink("Create New", "Create") generates @Html.DisplayNameFor(model => model.Age) Create New 10 Copyright © 2023 Deloitte Development LLC. All rights reserved. HTML Helper—Commonly Used Strongly Typed HTML Helper Corresponding HTML Helper Html.ActionLink Anchor link Html.TextBoxFor Text box Html.TextAreaFor Text area Html.CheckBoxFor Checkbox Html.RadioButtonFor Radio button Html.DropDownListFor Dropdown, combo box Html.ListBoxFor Multiselect list box Html.HiddenFor Hidden field Html.PasswordFor Password text box Html.DisplayFor Html text Html.LabelFor Label Generates Html controls based on the data type of specified Html.EditorFor model property, for example, textbox for string property, numeric field for int, double, or other numeric types 11 Copyright © 2023 Deloitte Development LLC. All rights reserved. Razor View Engine Razor is one of the many view engines supported in ASP.NET MVC. Razor Syntax Razor enables you to write a mix of HTML and server-side code using Use @ to write server-side code. C# or Visual Basic. Server-side code block starts with The Razor view with the Visual Basic syntax has.vbhtml file extension @{ server-side code block here } and C# syntax has.cshtml file extension. Use @: or to display text Razor syntax has the following characteristics: from code block. − Compact: The Razor syntax is compact, which enables you to if condition starts with @if{ } minimize the number of characters and keystrokes for loop starts with @for required to write a code. @model allows you to use model object − Easy to Learn: The Razor syntax is easy to learn where you can use anywhere in the view. your familiar language C# or Visual Basic. − Intellisense: The Razor syntax supports statement completion within Visual Studio. 12 Copyright © 2023 Deloitte Development LLC. All rights reserved. Razor Syntax Type C# Razor Syntax Output Razor syntax demo Razor syntax demo Inline expression @DateTime.Now.ToShortDateString() 08-09-2014 @{ var date = DateTime.Now.ToShortDateString(); var message = "Hello World"; Today's date is: 08-01-2020 Multistatement Code block } Hello World! Today's date is: @date @message 13 Copyright © 2023 Deloitte Development LLC. All rights reserved. Razor Syntax (Cont.) Type C# Razor Syntax Output @{ var date = DateTime.Now.ToShortDateString(); string message = "Hello World!"; Today's date is: 08-01-2020 Display Text from Code Block Today's date is: @date Hello World! @message } @if(DateTime.IsLeapYear(DateTime.Now.Year) ) { @DateTime.Now.Year @:is a leap year. If-else condition } 2014 is not a leap year. else { @DateTime.Now.Year @:is not a leap year. } 14 Copyright © 2023 Deloitte Development LLC. All rights reserved. Razor Syntax (Cont.) Type C# Razor Syntax Output 0 @for (int i = 0; i < 5; i++) { 1 for loop @i.ToString() 2 } 3 4 15 Copyright © 2023 Deloitte Development LLC. All rights reserved. Razor Syntax (Cont.) Type C# Razor Syntax Output @model Student Student Detail: Student Detail: Model Student ID: @Model.StudentId Student ID: 1 Student Name: @Model.StudentName Student Name: John Age: @Model.Age Age: 18 @{ string str = ""; if(1 > 0) Declare Variables { Hello World! str = "Hello World!"; }} @str 16 Copyright © 2023 Deloitte Development LLC. All rights reserved. Action Result MVC framework consists of various result classes that can be Example: returned from an action method. The result classes [HttpGet] represent various types of responses such as HTML, file, 0 references string, and JSON. public ActionResult Create() The ActionResult class is a base class of the result classes { (shown in the next slide), so it can be a return type of the return View(); action method, which returns any type of result. However, } an appropriate result class can also be specified as a return type of action method. [HttpPost] 0 references The Create() method of StudentController as shown in the public ActionResult Create (Student StdDetails) displayed example uses View() method to return { ViewResult, which is derived from the ActionResult. The Student sd = new Student(); View() method is defined in the base controller class. sd.StudentId = 8; The Create() method also contains different methods, sd.StudentName = StdDetails.StudentName; which automatically returns the result as shown in the next sd.Age = StdDetails.Age; slide. TempData["NewStudent"] = sd; return RedirectToAction("Index"); } 17 Copyright © 2023 Deloitte Development LLC. All rights reserved. Action Result (Cont.) Result Class Represents ViewResult HTML and markup EmptyResult No response ContentResult String literal FileContentResult/ FilePathResult/ FileStreamResult The content of a file JavaScriptResult A JavaScript script JsonResult JSON that can be used in AJAX RedirectResult Redirection to a new URL RedirectToRouteResult Another action of same or other controller PartialViewResult Returns HTML from the partial view HttpUnauthorizedResult Returns the HTTP 403 status 18 Copyright © 2023 Deloitte Development LLC. All rights reserved. Layout View An application may contain some common parts in the user interface (UI), which remain the same throughout the application, such as the Header logo, header, left navigation bar, right bar, or footer section. ASP.NET MVC introduced a Layout view, which contains these common UI parts so that we don't have to write the same code on every page. The layout view is the same as the Master page of the ASP.NET webform application. Left Content Right For example, an application UI may contain the header, left menu Section Area Section bar, right bar, and footer section that remains unchanged on every page and only the center section changes dynamically as shown in the image. The layout view enables you to come up with a common site Footer template, which can be inherited in multiple views for uniform look and feel on various pages of an application. The layout view speeds up development, simplifies maintenance and eliminates duplicate coding. The layout view as shown in the image contains UI Fixed, Fixed, part of layout part of layout elements such as the header, left menu, right bar, and Dynamic, added at runtime footer Dynamic, added at runtime sections. It features a placeholder for the center section that changes dynamically. 19 Copyright © 2023 Deloitte Development LLC. All rights reserved. Layout View (Cont.) The Razor layout view has the same extension as other views:.cshtml or.vbhtml. The Layout views are shared with multiple views, which is why they must be stored in the shared folder. They Layout view can be set in multiple ways, by using _ViewStart.cshtml or setting up the path of the layout page using the Layout property in the individual view or by specifying the layout view name in the action method. _ViewStart.cshtml is part of the Views folder by default. It sets up the default layout page for all the views in the folder and its subfolders using the Layout property. You can assign a valid path of any Layout page to the Layout property. 20 Copyright © 2023 Deloitte Development LLC. All rights reserved. Layout View (Cont.) The ASP.NET MVC layout view renders the child views using the following methods: Methods Descriptions Renders the part of the child view that is not within a named section RenderBody() The Layout view must include RenderBody() method Renders the content of the named section and specifies whether the RenderSection(string name) section is required Has the RenderSection() optional in the Layout view 21 Copyright © 2023 Deloitte Development LLC. All rights reserved. Layout View (Cont.) Index.cshtml Main Content @section LeftSection { content } Header Left Content Right Section Area Section Footer 22 Copyright © 2023 Deloitte Development LLC. All rights reserved. Partial View The partial view is a reusable view, which can be used as a child view in multiple other views. It eliminates duplicate coding by reusing the same partial view in multiple places. You can use the partial view in the layout view as well as other content views. For example, we can create a partial view for a navigation bar, so that we can use the same navigation bar in multiple layout views without rewriting the same code everywhere. The partial view can be rendered using the Html.Partial(), Html.RenderPartial(), or Html.RenderAction() methods. Each method serves different purposes. Let's have an overview of each method and then see how to render a partial view using these methods. 23 Copyright © 2023 Deloitte Development LLC. All rights reserved. Html.Partial() The Helper method renders the specified partial view. It accepts the name of the partial view as a string parameter and returns MvcHtmlString. It returns html string, so that you have a chance of modifying it before rendering. The table below lists the overloads of the partial Helper method. Helper Methods Descriptions MvcHtmlString Html.Partial (string partialViewName) Renders the given partial view content in the referred view MvcHtmlString Html.Partial Renders the partial view content in the referred view, and the model parameter passes (string partialViewName, object model) the model object to the partial view 24 Copyright © 2023 Deloitte Development LLC. All rights reserved. Html.Partial() Helper Methods Descriptions MvcHtmlString Html.Partial( string partialViewName, Renders the partial view content in the referred view, and the view data parameter ViewDataDictionary passes view data dictionary to the partial view viewData) MvcHtmlString Html.Partial (string partialViewName, Renders the partial view content in the referred view, and the model parameter passes object model, ViewDataDictionary the model object, and the view data passes the view data dictionary to the partial view viewData) 25 Copyright © 2023 Deloitte Development LLC. All rights reserved. Html.RenderPartial() The Helper method is the same as the partial method except that it returns void and writes resulted HTML of a specified partial view into an HTTP response stream directly. The table below lists the overloads of the render partial Helper method. Helper Methods Descriptions RenderPartial(String partialViewName) Renders the specified partial view RenderPartial(String partialViewName, Object model) Renders the specified partial view and sets the specified model object RenderPartial(String Renders the specified partial view, replacing its ViewData property partialViewName, ViewDataDictionary viewData) with the specified ViewDataDictionary object RenderPartial(String Renders the specified partial view, replacing the partial view's partialViewName, Object model, ViewData property with the specified ViewDataDictionary object and ViewDataDictionary viewData) sets the specified model object 26 Copyright © 2023 Deloitte Development LLC. All rights reserved. Html.RenderAction() Helper method invokes a specified controller and action and renders the result as a partial view. The specified Action method must return PartialViewResult using the Partial() method. The table below lists the overloads of the Render Action helper method. Helper Methods Descriptions Calls the particular child action method and renders the RenderAction(String actionName) result in the parent view RenderAction(String actionName, Calls the particular child action method using the defined Object routeValue) parameters and renders the result inline in the parent view RenderAction(String actionName, Calls the particular child action method using the defined String controllerName) controller name and renders the result inline in the parent view RenderAction(String actionName, Calls the particular child action method using the defined RouteValueDictionary routeValues) parameters and renders the result inline in the parent view 27 Copyright © 2023 Deloitte Development LLC. All rights reserved. Html.RenderAction() (Cont.) Helper Methods Descriptions RenderAction(String actionName, String Calls the particular child action method using the defined parameters and controller name controllerName, Object and renders the result inline in the parent view routeValue) RenderAction(String actionName, String controllerName, Calls the particular child action method using the defined parameters and controller name RouteValueDictionary and renders the result inline in the parent view routeValues) 28 Copyright © 2023 Deloitte Development LLC. All rights reserved. Model The model represents domain specific data and business logic in MVC architecture. It maintains the data of the application. The model objects retrieve and store model state in the persistence store like a database. The model class holds data in public properties. All the model classes reside in the Model folder in the MVC folder structure. Attributes can be applied to control the display of data. Attributes are available in the System.ComponentModel.DataAnnotations namespace. 29 Copyright © 2023 Deloitte Development LLC. All rights reserved. Model (Cont.) Display DisplayColumnAttribute DisplayName UIHint. DisplayFormat Built in Attributes HiddenInput ReadOnly and ScaffoldColumn DataTypeAttribute 30 Copyright © 2023 Deloitte Development LLC. All rights reserved. Routing ASP.NET Web Forms works with an exact path ending with User Interface.ASPX extension (Example: http://domain/student.aspx). If the requested ASPX page is present at the location, then it is processed by.NET and a response is sent to the client, otherwise, HTTP 404 Not Found error is sent. HTTP 404 Not Found ASP.NET introduced routing to eliminate the need of Parse URL mapping each URL with a physical file. Routing allows the Processed Response URL pattern that points to the request handler, which can be a file or class. While in ASP.NET webform application, the request handler is.ASPX file, in MVC, it is the controller class Route Find Matching Route and action method. For example, Table http://domain/student.aspx ASP.NET Webform path maps to http://domain/student MVC route, where the student controller is having the Index No Found Action method. Route specifies the URL pattern and handler information. All Yes configured routes of an application are saved in the route table to be used by the routing engine to identify the suitable handler class or file for meeting an incoming.NET Framework request. 31 Copyright © 2023 Deloitte Development LLC. All rights reserved. Routing Configuration Every MVC application must configure at least one route pattern. Visual Studio adds a default route pattern in RouteConfig class in RouteConfig.cs under the App_Start folder. public static void RegisterRoutes (RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{ID}", defaults: new { controller = "Home", action = "Index", ID = UrlParameter.Optional } ); } 32 Copyright © 2023 Deloitte Development LLC. All rights reserved. Routing URL Pattern The URL pattern excludes domain name from URL. http://localhost:80/{controller}/{action}/{ID} Few examples of URL patterns are given in the table below: URL Controller Action ID http://localhost/home HomeController Index null http://localhost/home/index/123 HomeController Index 123 http://localhost/home/about HomeController About null http://localhost/home/contact HomeController Contact null http://localhost/student StudentController Index null http://localhost/student/edit/123 StudentController Edit 123 33 Copyright © 2023 Deloitte Development LLC. All rights reserved. Route Constraints Parameter values can be restricted to specific data types or patterns using constraint objects. Constraint pattern can be defined using the regular expression. If the data type or pattern doesn’t match, then the ASP. Net MVC Routing logic will ignore that parameter. public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{ID}", defaults: new { controller = "Home", action = "Index", ID = UrlParameter.Optional }, constraints: new { ID = @"\d+" } ); } 34 Copyright © 2023 Deloitte Development LLC. All rights reserved. Area A large ASP.NET MVC application In Visual Studio 2019 and later, includes many controllers, views, and the area can be added using model classes, which is why it can be Add > New scaffolded item…, difficult to maintain with the default while in older Visual Studio, it ASP.NET MVC project structure. was available directly in the Add Context menu. ASP.NET MVC introduced a new feature New area specific route configuration called area for this. Area allows partition is added in the Area folder. of a large application into smaller units where each unit contains a separate MVC folder structure, which is the same as the default MVC folder structure. 35 Copyright © 2023 Deloitte Development LLC. All rights reserved. Area (Cont.) public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Intake_default", "Intake/{controller}/{action}/{ID}", new action = "Index", ID = UrlParameter.Optional } ); } 36 Copyright © 2023 Deloitte Development LLC. All rights reserved. State Management State Management HTTP is a stateless protocol. By design, it does not know about the previous request and its data. If data is needed between redirection, then it needs to be Hidden Field maintained by one of the state management techniques. ViewData Besides ASP.NET provided mechanisms like SessionState and ApplicationState, there are options available for an MVC application to maintain state. Cookie Let’s look at these options in the next slide. ViewBag Query String TempData 38 Copyright © 2023 Deloitte Development LLC. All rights reserved. Classic Hidden Field Cookies Query String Is an HTML element like Are the small text stored on Is a key-value pair and textbox that is not the client side passed as part of the URL. rendered on UI Are generally. used to store Can be retrieved either by Can be created with basic user information, using the Request object HTML tag or Can be created and Action method. using HTML helper retrieved using.NET code http://localhost:80/int @Html.HiddenFor ake/process?caseid=4045 (h => x.ID) 39 Copyright © 2023 Deloitte Development LLC. All rights reserved. Classic (Cont.) Set Cookie Retrieve Cookie HttpCookie cookie = new Request request = HttpCookie("TestCookie"); this.ControllerContext.HttpContext.Request; cookie.Value = "This is test cookie"; this.ControllerContext.HttpContext.Response.C if ookies.Add(cookie); (request.Cookies.AllKeys.Contains("TestCookie")) { HttpCookie cookie = request.Cookies["TestCookie"]; string cookieValue = cookie.Value; } Additional Points for generic state management techniques It is easy to use these generic options—Hidden Fields, Cookies, and Query String. All these state management options store data on the client side and can be accessed/manipulated by the user. For security reasons, these options should not be used to store confidential details, such as Social Security Number (SSN). 40 Copyright © 2023 Deloitte Development LLC. All rights reserved. ViewData Is a dictionary object Maintains key-value pair Set ViewData Is derived from ViewDataDictionary ViewData["Msg"] = "Welcome to this site"; Is used to share data from the controller to view Has the values used only in the current request and are not Retrieve ViewData available in the subsequent request Requires null check and type casting before accessing @if(ViewData["Msg"] !=null) the value { @ViewData["Msg"].ToString(); Throws an exception, if the value is accessed in view without } defining it in the controller 41 Copyright © 2023 Deloitte Development LLC. All rights reserved. ViewBag Is similar to ViewData Has a wrapper around it Uses dynamic type introduced in C# 4.0 Set ViewData Doesn’t require a null check and type casting before ViewBag.Msg = "Welcome to this site"; accessing its value Doesn’t throw any exception, if used without defining it first Retrieve ViewData @ViewBag.Msg 42 Copyright © 2023 Deloitte Development LLC. All rights reserved. TempData TempData is a dictionary object and is derived from TempDataDictionary. It is used to transfer data for current or subsequent requests. TempData value can be persisted in multiple ways. Don’t Read Data Keep Data Peek Data During multiple redirects, data To persist value for the To get the value without is persisted in TempData till its subsequent request even after clearing TempData, use peek() value is read. being read, call keep() method method with the variable name. on TempData. 43 Copyright © 2023 Deloitte Development LLC. All rights reserved. Model Binding Model Binding In ASP.NET, QueryString and Form Post values are available as part of the HttpContext Request object. In ASP.NET WebForms, these values are retrieved to a local variable/property using Request.QueryString["ID"] and Request.Form["Name"]. In ASP.NET MVC, this value retrieval is done automatically. With Model binding, the MVC framework converts HTTP request values to action method parameters. Model binding supports both the primitive and complex data types. 45 Copyright © 2023 Deloitte Development LLC. All rights reserved. Primitive Types HttpGET Request embeds data into a query string. MVC public ActionResult Client(int ID) framework automatically converts a query string to the action { method parameters. List clients = ClientManager.GetClients(); For example, the query string "ID" in the GET request would Client client = clients.SingleOrDefault(c => c.ID == ID); automatically be mapped to the ID parameter of the Client() return View(client); action method. } There can be multiple parameters in the action method with different data types. Query string values will be converted into public class Client parameters based on the matching name. { For example, 0 references http://localhost:8080/Service/Client?ID=1&name=John public int ID { get; set; } would map to ID and name parameter of the action method. 1 reference public string Name { get; set; } 0 references public string AddressLine01 { get; set; } 0 references public string AddressLine02 { get; set; } 0 references public string City { get; set; } } 46 Copyright © 2023 Deloitte Development LLC. All rights reserved. Complex Types Model binding also works on complex types. Model binding in the MVC framework automatically converts form field data of HTTP post request to the properties of a complex type parameter of an action method. MVC framework automatically maps form collection values to the client type parameter when the form submits HTTP post request to save action method. [HttpPost] Client 0 references Name: public ActionResult Save(Client client) { AddressLine01: ClientManager cm = new ClientManager(); cm.Save(client); // Save client info to DB AddressLine02: return View(client); } City: Save 47 Copyright © 2023 Deloitte Development LLC. All rights reserved. Bind Attribute MVC framework also allows selective binding of property. [Bind] attribute is used to specify exact properties that the model binder should include or exclude while performing model binding. For example, Save action method will exclude binding of ID property. [HttpPost] 0 references public ActionResult Save([Bind(Exclude = "ID")] Client client) { ClientManager cm = new ClientManager(); cm.Save(client); // Save client info to DB return View(); } 48 Copyright © 2023 Deloitte Development LLC. All rights reserved. Filters ASP.NET MVC Filter is a custom class where custom logic is written to execute before or after an action method executes. Filters can be applied to an action method or controller in a declarative or programmatic way. Declarative means applying a filter attribute to an action method or controller class and programmatic means implementing a corresponding interface. Example: [HandleError] built-in filter renders Error.cshtml view from a shared folder in case of an unhandled exception in executing action method. Filters Interfaces Descriptions Used to implement authentication and Authorization Filters IAuthorizationFilter authorization for controller actions Contains logic that is executed before and after a Action Filters IActionFilter controller action executes Contains logic that is executed before and after a Result Filters IResultFilter view result is executed Handles errors raised by either controller actions Exception Filters IExceptionFilter or controller action results 49 Copyright © 2023 Deloitte Development LLC. All rights reserved. Exception Handling Simple traditional.NET mechanism to handle exceptions. Try block encapsulates code logic that can error out. Using try, catch, and finally One or more catch block catches exceptions and handles it. Finally block generally holds code for clean-up activities. ExceptionContext is available as the parameter. By overriding "OnException" method View name is defined in the result, which gets rendered when an error occurs. in controller Exception and other details can be passed to view as Model. Attribute [HandleError] is applied to the action method. In case of exception, generic error view, as configured in web.config is Using "HandleError" Attribute rendered on the screen. Exception type and specific view can be specified at the attribute level. 50 Copyright © 2023 Deloitte Development LLC. All rights reserved. Exception Handling (Cont.) This is a combination of ‘OnException’ and ‘HandleError’. OnException allows exception handling at the controller level while Inheriting from "HandleErrorAttribute HandleError provides ease of attribute. Provides reusability by extending exception handling for multiple controllers. Custom errors can be configured in web.config. Handling HTTP Errors Different routes can be defined for different HTTP error codes. "Application_Error" event can be overridden in Global.asax. Global Exception Handling All the unhandled exception will be caught here and can be handled. 51 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Labs Development Environment Tools Installation and Setup Integrated development environment (IDE): Visual Studio 2022 Community Edition Database System: SQL Server 2019 Developer Edition SQL Server Management Studio API Tool: Postman 53 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Activity 1 Activity Details: Shopping Cart Module Modify all product views to show Add to Cart button with the option to specify quantity. Create a card model. Create the controller action methods to Add to cart operation. Problem Statement Use session object to store cart entries (understand the option to persist cart to the database). Use jQuery AJAX to add product to the cart. 54 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Activity 2 Activity Details: Order Module Create a Data Access Layer (DAL) to get the order list. Create a view for the order list. Problem Statement Create a controller action method for the order list. Tie the controller action methods to Business > DAL that are created earlier. Run the application functionality to test the code. 55 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Activity 3 Activity Details: DAL for eCommerce System Create a new class library project for DAL. Entities: − Product Operations: Problem Statement − Create Product − Update Product − Get Product By ID − Get Products (All) 56 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Activity 4 Activity Details: Admin Module Add a new ASP. Net MVC web application. Create models for a product. Create views for a product. Create controller action methods for the following operations: Problem Statement − Get all products. − Update products. (approval flag) Tie the controller action methods to Business > DAL that were created earlier. Run the application functionality to test the code. 57 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Activity 5 Activity Details: Security Module Create a model for the user login. Create a view for the user login. Create a DAL for the user login. Create controller action methods for the user sign-in form: Problem Statement − User Sign-in Form (HttpGet) − User Sign-in Submit (HttpPost) Provide the status or validation error. Run the application functionality to test the code. 58 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Activity 6 Activity Details: Shopping Cart Module Create a view for the shopping cart list/check out. Create controller action methods to list all cart products. Problem Statement Have each row with the following action buttons: − Update: To allow users to change the quantity of product in the cart − Delete: To allow users to completely remove the product from the cart 59 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Activity 7 Activity Details: Order Module Create an order model. Create a DAL for order. Create the controller action method to save the order. Problem Statement Show a status or validation message. Tie the controller action methods to Business > DAL that were created earlier. Run the application functionality to test the code. 60 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Activity 8 Activity Details: ASP.NET MVC Web Application for eCommerce System—Admin Module Create a DAL method to save new products. Create a view for creating new products. Create controller action methods for product creation. Problem Statement − New Product Form (HttpGet) − New Product Save (HttpPost) Tie the controller action method to Business > DAL. Run the application functionality to test the code. 61 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Activity 9 Activity Details: Business Layer for eCommerce System Create a new console application for the batch job. Read records from the.csv file. Load all records in the database table. Problem Statement − Entities − Product − Operations Create products (bulk). 62 Copyright © 2023 Deloitte Development LLC. All rights reserved. Hands-On Activity 10 Activity Details: ASP.NET MVC Web Application for eCommerce System (Both User and Admin Modules) User Module Reuse the DAL method to get all products earlier that were created for the Admin module. Create a view to list all products. Create controller action methods for product list. Tie controller action method to Business > DAL. Problem Statement Admin Module Add a new column ‘action’ with following link buttons: − Detail − Edit − Delete Run the application functionality to test the code. 63 Copyright © 2023 Deloitte Development LLC. All rights reserved. Summary Here are the key learning points of the module. ASP.NET MVC is a web framework based on the MVC architecture. Model binding supports both primitive and complex data types. 64 Copyright © 2023 Deloitte Development LLC. All rights reserved. Thank You About Deloitte Deloitte refers to one or more of Deloitte Touche Tohmatsu Limited, a UK private company limited by guarantee ("DTTL"), its network of member firms, and their related entities. DTTL and each of its member firms are legally separate and independent entities. DTTL (also referred to as "Deloitte Global") does not provide services to clients. In the United States, Deloitte refers to one or more of the US member firms of DTTL, their related entities that operate using the "Deloitte" name in the United States and their respective affiliates. Certain services may not be available to attest clients under the rules and regulations of public accounting. Please see www.deloitte.com/about to learn more about our global network of member firms. This communication contains general information only, and none of Deloitte Touche Tohmatsu Limited ("DTTL"), its global network of member firms or their related entities (collectively, the "Deloitte organization") is, by means of this communication, rendering professional advice or services. Before making any decision or taking any action that may affect your finances or your business, you should consult a qualified professional adviser. No representations, warranties or undertakings (express or implied) are given as to the accuracy or completeness of the information in this communication, and none of DTTL, its member firms, related entities, employees or agents shall be liable or responsible for any loss or damage whatsoever arising directly or indirectly in connection with any person relying on this communication. DTTL and each of its member firms, and their related entities, are legally separate and independent entities. Copyright © 2023 Deloitte Development LLC. All rights reserved.

Use Quizgecko on...
Browser
Browser