Presentation is loading. Please wait.

Presentation is loading. Please wait.

An introduction to ASP.Net with MVC Nischal S

Similar presentations


Presentation on theme: "An introduction to ASP.Net with MVC Nischal S"— Presentation transcript:

1 An introduction to ASP.Net with MVC Nischal S
ASP.Net MVC An introduction to ASP.Net with MVC Nischal S

2 PRIOR understanding Understanding C# programming language
Understanding on basic ASP.Net and HTML. Basic understanding of design patterns and it’s purpose

3 Topics Understanding MVC ASP.Net request life cycle
Connecting Model, View and Controller. Routing, Actions and Model Binding Security and Caching ASP.Net WPI Demo

4 Understanding MVC “The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly. MVC design pattern.” * Model-View and Controller Three components Model – Data representation View – UI presentation, display data Controller– link between model and view, handles events Testability, Maintainability and Extensibility -separating concerns within an application Model - classes that describes the data View- pure HTML, which decides how the UI is going to look like. Controller- handles communication from the user, overall application flow, and application-specific logic Why MVC: -explicit separation of concerns does add a small amount of extra complexity to an application’s design. separating data access logic from display logic Enables Test Driven Development (TDD). Following the design of stateless nature of the web. *

5 Understanding MVC View Model
Views are for encapsulating presentation logic. They will not contain application logic or database retrieval code. Application logic will be handled by the controller. A view renders the appropriate UI by using the data that is passed to it from the controller. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. Model Objects in Model are the parts of the application that implement the domain logic or business logic.Business logic handles the data that is passed between the database and the UI.For example, in an Employee management system, the model keeps track of the employees in payroll and the logic to determine whether an employee is a Individual contributor or Manager.The model in application will update the database when an employee is added and updated. Also model stores and retrieves model state in a database. View: -Controller action methods handle an incoming Web request. These action methods use the incoming parameter values to execute application code and to retrieve or update data model objects from a database. The methods then select a view that renders a response to a browser. -MVC framework uses custom types (ViewPage, ViewMasterPage, and ViewUserControl) that inherit from the existing ASP.NET page (.aspx), master page (.master), and user control (.ascx) types as views. Model: -access data from a persistent store, such as SQL Server, and perform the business logic on that data. -application specific, directly use ADO.NET DataSet or DataReader objects, or you can use a custom set of domain objects -Model class is located in the folder structure of the application - model class in an ASP.NET MVC application does not directly handle input from the browser, nor does it generate HTML output to the browser.

6 Understanding MVC Controller
Controllers handle user interaction, works with model, and to display selects a view to render. The view only displays information; the controller handles and responds to user input and interaction. For example, the controller gets query- string and passes query string to the model. The model use these values to get data from the database. Controller: Controller class is responsible for the following processing stages: -Locating the appropriate action method to call and validating that it can be called. -Getting the values to use as the action method's arguments. -Handling all errors that might occur during the execution of the action method.

7 ASP.Net request life cycle
ASP.Net request life cycle is sequence of events that happen every time a http request is made on browser with entry point in application being URL routing module. URL routing module matches incoming URL to routes that are defined. The Controllers are created and initialized, the controller then a component called Action invoker finds an selects an appropriate Action method to invoke in controller. Before Action method is called, Model Binding takes place and it maps the data from HttpRequest to parameters into our Action Methods. Action Filters are called before and after the method creates an Action Result. If the result is a View type, the View Engine is called and it’s responsible for rendering view by finding it. If the result is not a view, the ActionResult executes itself. Routing: The entry point for every MVC Application begins with Routing. After the application receives the request, it uses URL Routing Module to handle the request. The routing module is responsible for matching the incoming urls with the routes defined in the application. All routes have an associated MVC Route Handler. If the request is matched with one of the routes defined into application, the MVC Route Handler executes and retrieves an instance of MVC HttpHandler. Controller initialization: The MVC HttpHandler begins the process of initializing and executing a controller. MVC framework converts our routing data into a specific controller that handle the request. This is accomplished by Controller Factory and Activator. This is the step where dependency injection are resolved. The next major step after controller creation is action execution. Action execution: A component called Action Invoker finds and selects an appropriate Action Method to invoke in our controller. Before the method is called, Model Binding takes place and it maps the data from HttpRequest to parameters into our Action Methods. Action Filters are called before and after the method creates an Action Result. Result execution: MVC separates declaring of the result from executing the result. If the result is a View type, the View Engine is called and it’s responsible for finding and rendering our view. If the result it’s not a view, the ActionResult executes on it’s own.

8 Connecting Model, View and Controller.
1 3 4 2 -ASP.Net MVC project from an empty project template creates basic MVC project with minimal predefined content. - -To remove the 404 Not Found error, we need to add a controller, which handles all the incoming requests. Let’s get started Create a new ASP.Net application. Select ASP.Net Empty application, make sure to check MVC so that underlying folders are created for segregation.[Uncheck Host in cloud] Running the application throws 404 Error as there is no Controller to handle request. Hence create a Controller under Controllers Folder and name it as HomeController.cs Return a string from Index(), as this currently pointed as default in RoutingConfig.cs

9 Connecting Model, View and Controller
1 Default routing maps to HomeController. If the Default is replaced in MapRoute() Function, there will be no controller to route hence will html error. We Create another controller entry as Employee. Create a Employee Controller, add function List() as per MapRoute(), then run the application. Modify the URL, such that controller to call in Employee/List 2 No default then - HTTP Error – Forbidden After point 1, running the application throws 404 Not Found error, as there is no Employee Controller. At this point, we understand how routing works and how controllers are called. 3

10 Connecting Model, View and Controller
3 6 Controllers, Action and Model Controllers are recipients of http request and thus selects model to use to fetch data and passes the same to respective View. Here under Employee Controller we create 2 actions – List and Search. Note Default is the List if no action is specified. By default under Employee Controller List is called as specified in the RouteConfig.cs. This lists all the employee. By specifying Search in URL, the Search Action is invoked and {id} is taken as input to search for particular employee Non specified/invalid inputs are to be handled as well. 4 5

11 Routing, Actions and Model Binding
1 Routing Routing directs an HTTP request to a controller and the functionality is implemented in System.Web.Routing. The MVC framework uses routing to direct a request to a controller. The Global.asax file is that part of your application, where you will define the route for your application. RouteConfig.cs contains class, which contains one method RegisterRoutes and mapping URL to specific controller action. The global application resource dictionary is in the App.xaml file. In this file you can include several resource dictionaries as a Merged Dictionary.  An action is just a method on the controller. It can also pick parameters out of that URL and pass them as parameters into the method. URL arrive in the form of {controller}/{action}/{id}, then the first piece is the controller name, second piece is the action name, and the third piece is an ID parameter. Demo:2

12 Routing, Actions and Model Binding
1 3 Actions return different types of action results. The ActionResult class is the base for all action results. Default Action invoked is Note: [ActionName("Demo1")]– Redirect to Action search Employee with Id =11002 [First load the employees] [ActionName("Demo2")] – Redirect to route with Employee and List [ActionName("Demo3")] – Show a static file text in page – XML/Text [ActionName("Demo4")] – Return JSON to page on request Demostrate different types of Action Results. ActionResult type is base for all action results. The MapRoute() is updated with the controller/ Action and params. Action Results supports further types as shown in Figure 3. 2 Demo:3

13 Routing, Actions and Model Binding
6 4 5 “HTML.BeginForm” writes an opening Form Tag. It also ensures that the method is going to be “Post”, when the user clicks on the “Delete” button. Model Binding (Create, Read, Update and Delete) Open the EmployeeController.cs, Let us create operations for Create, List , Edit and Delete. For example, we take the action of Delete, in Delete functionality we delete the item from collection of given Id. Right click on Delete function, Select option Add View. Select the Template for Delete and then select Model Class as “Employee”. This makes sure the Employee class is taken to generate a templated View for Delete. In the templated view, notice ActionLink(), which contains “ActionLinkName”, “Action”, if there are route values(params) to pass then those can also be provided.

14 Routing, Actions and Model Binding
9 7 Model Binding (Create, Read, Update and Delete) Now you will notice there are two Actions for Delete, GET and POST. The GET gets the records for confirmation page and once the button in Step 6 is clicked, the form is posted, thus Delete Action in [HttpPost] performs Delete. The Delete could be DB or collection and then RedirectToAction() is called go back to Index. Click on Delete, then you will notice GET Action for Delete is called passing Employee Id as param. From Index View which was created under the List Template, you will notice the ActionLink() for Delete- Specifying LinkName, Action to call and params. Delete View created from step 4 to 6, is displayed with data and on Delete Button Click the Action for Delete using POST is called and collection/DB is updated. -- Shows the Main Employee List -- Click on Edit, Delete – Details not implemented as it is easy and similar to Edit Action using GET -- Create Employee implemented During Create/ Edit, MVC Framework figures out that ID field is mentioned in the model class and hence it needs to be prevented from getting edited, that is why it is marked as hidden. The Html.LabelFor HTML Helper creates the labels on the screen. The Html.ValidationMessageFor helper displays proper error message if anything is wrongly entered while making the change. 8 10

15 SECurity and CACHING 1 Security using Authorize, AuthorizeAttribute is an ActionFilter, it executes before the associated controller action. This attribute makes sure the such controller method or controller(class level) is not accessible by anonymous user. Upon executing the code and trying to invoke the controller Action Public, we see that information/ method is accessible without login. While trying to access controller Action Private, we see that it is not accessible and would auto redirected to login page. -- Shows the Main Employee List -- Click on Edit, Delete – Details not implemented as it is easy and similar to Edit Action using GET -- Create Employee implemented 2 3

16 SECurity and CACHING 1 Security using Authorize, AuthorizeAttribute is an ActionFilter, it executes before the associated controller action. This attribute makes sure the such controller method or controller(class level) is not accessible by anonymous user. Upon executing the code and trying to invoke the controller Action Public, we see that information/ method is accessible without login. While trying to access controller Action Private, we see that it is not accessible and would auto redirected to login page. Once user is logged in he will be able to access this controller method. Apply Authorize filter to the controller itself and now every action inside of this controller will require the user to be authenticated. [AllowAnonymous] - override this authorization rule with another attribute on controller method. [Authorize(Users = -- Allow only specific user to access controller method 2 3

17 SECurity and CACHING 1 Cache profile could be created in Web.config with details on duration. Hence no need to recompile code when cache duration to be updated or modified. Also one profile for multiple controllers. The attribute [OutputCache] could be used on controller to specify the caching option. The controller Action Details will be served from cache for a duration of 3mins. 2 Apply Authorize filter to the controller itself and now every action inside of this controller will require the user to be authenticated. [AllowAnonymous] - override this authorization rule with another attribute on controller method. [Authorize(Users = -- Allow only specific user to access controller method

18 ASP.Net Web API 1 HTTP as a powerful platform for building APIs that expose services and data. HTTP is simple,stateless and flexible.ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. Seamlessly connect mobile, desktop browser or other end points. Similar to ASP.Net MVC application, ASP.Net Web API has a model and controller. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. We use the same model discussed in previous slide, create a new controller this time, select “WEB API 2 Controller”. Implementation of controller is done to GetList and Get by Id 2 The controller defines two methods that return products: -The GetList method returns the entire list of Employees as an IEnumerable<Employee> type. -The Get method looks up a single Employee by its ID. Controller MethodURI GetAllProducts /api/products GetProduct /api/products/id

19 Thank YOU


Download ppt "An introduction to ASP.Net with MVC Nischal S"

Similar presentations


Ads by Google