Web Programming using .NET PDF

Document Details

TenaciousNumber

Uploaded by TenaciousNumber

Darshan University, Rajkot

Naimish R. Vadodariya

Tags

web programming .NET ASP.NET Core computer science

Summary

This document provides an introduction to ASP.NET Core, a web framework used to build various types of web applications. It includes topics such as project creation, MVC architecture, and data passing techniques.

Full Transcript

Web Programming using.NET #2305CS311 Unit-2 Introduction to ASP.NET Core Prof. Naimish R. Vadodariya Computer Science & Engineering Department Darshan University, Rajkot [email protected] 8866215...

Web Programming using.NET #2305CS311 Unit-2 Introduction to ASP.NET Core Prof. Naimish R. Vadodariya Computer Science & Engineering Department Darshan University, Rajkot [email protected] 8866215253  Outline Looping Introduction to ASP.NET Core Version History Advantages How to Create a Project? Project Layout MVC Architecture ASP.NET Core Life Cycle Action & Non Action Methods Action Verbs Data Passing Techniques Introduction to ASP.NET Core Section – 2.1 Introduction: ASP.NET Core  ASP.NET Core provides a generalized web framework that you can use to build a wide variety of applications.  We can use ASP.NET Core to build server-rendered web applications, backend server applications, HTTP APIs that can be consumed by mobile applications, and much more.  ASP.NET Core is a cross-platform, open-source application framework that we can use to build dynamic web applications quickly.  It runs on.NET 8, which is the latest version of.NET Core - a high-performance, cross-platform, open-source runtime.  We can build and run it on any platform.  Microsoft launched ASP.NET web framework along with.NET Framework 1.0 in 2002, It was designed to run on Windows platform.  In 2016, Microsoft launched ASP.NET Core (.NET Core 1.0) framework which can run on Windows, Mac & Linux. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 4 ASP.NET Core Version History Cont.. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 5 Advantages: ASP.NET Core  Open Source  Cross-platform development and deployment  Modular Features  Focus on performance as a feature  A simplified hosting model  The option to package.NET with an app when publishing for standalone deployments Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 6 What Type of Application Can You Develop with ASP.NET Core?  Web: ASP.NET Core MVC, Web API, Razor Pages, and Micro services  Mobile  Console  Desktop Applications  IoT  ML  Gaming Applications  Cloud Applications  & Many More… Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 7 Creating a MVC Project Section – 2.2 Creating a MVC Project  First of all, open Visual Studio 2022 and then click on the Create a new project tab as shown in the image. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 9 Creating a MVC Project Cont..  From this window, select “C#”, “All Platforms” and “Web” from the respective dropdowns as highlighted below.  Search for the Model-View-Controller template.  Select “ASP.NET Core Web App (Model-View-Controller)” as highlighted below and click on the “ Next” button as shown in the image. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 10 Creating a MVC Project Cont..  Once you click on the Next button, it will open the Configure Your New Project window.  Give an appropriate name for the project DotNetCoreDemo, set the location where you want to create this project, and the solution name for the ASP.NET Core Web application.  And finally, click on the Next button as shown in the image. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 11 Creating a MVC Project Cont..  Once you click on the Next button, it will open the following Additional Information window.  Here, you need to select “Framework” – “.NET 8.0 (Long Term Support)”, “ Authentication type” – “None”.  You also need to uncheck the Configure for HTTPS and Do not use top-level statements check boxes and finally click on the Create button as shown in the below image. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 12 Creating a MVC Project Cont..  Once you click on the Create Button, the project is going to be created with the Model-View-Controller template with the following folder and file structure. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 13 MVC Project Structure  Dependencies is the place where the necessary dll’s for the application are stored.  Under the Properties menu, you will see a file called launchSettings.json which describes how a project can be launched.  It describes the command to run, whether the browser should be opened, which environment variables should be set, and so on.  Static content is hosted in the wwwroot folder. The content such as CSS, Javascript files and Bootstrap, jquery libraries need to be included here.  Controller, Models and Views folders are automatically created as we chose Web Application (Model-View-Controller).  appsettings.json is used to store information such as connection strings or application specific settings and these are stored in the JSON format as the file extension suggests.  Program.cs file in ASP.NET Core MVC application is an entry point of an application. It contains logic to start the server and listen for the requests and also configure the application. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 14 Model View Controller MVC Architecture Section – 2.3 MVC Architecture  MVC stands for Model View and Controller.  It is an architectural design pattern that means this design pattern is used at the architecture level of an application.  When we want to design an application, first we think about the architecture of application, and MVC plays an important role in the architecture.  MVC is a powerful and elegant means of separating concerns within an application.  So, the point is MVC is not a programming language, MVC is not a Framework, it is a design pattern.  MVC Design Pattern is basically used to develop interactive applications.  Each of these layers has very specific set of responsibility.  The Model layer contains the data.  The View renders the Model to the user and handles user interactions.  The View passes the user interactions to the Controller, which in turn builds the model and update the View. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 16 MVC Architecture Pattern Cont.. Separation of concerns  The Separation of concerns philosophy states that each component of the application is responsible for only one thing.  They should do not depend upon any other component as much as possible.  In other words, the components should be loosely coupled with other.  The application built using such a concept is easily testable, maintainable and extensible. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 17 Example: MVC Architecture URL: https://darshan.ac.in/how-to-apply View Controller Model  Selects the right controller to handle a request. Router  how-to-apply | Action method of particular controller will be called. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 18 View(s)  A view is a file with a “.cshtml” (for C# language) extension.  The meaning of cshtml = CS (C Sharp) + HTML  The Views in ASP.NET Core MVC are HTML templates with embedded Razor markup which generate content that sends to the client.  That means the view is a combination of programming language (C#) and HTML (Hypertext Mark-up Language).  The Views in ASP.NET Core MVC Application are generally returned from the Controller Action Method.  It is responsible for UI i.e. application data presentation.  That means we display information about the website on the browser using the views only.  A user generally performs all the actions on a view such as a button click, navigation, list, and other UI elements etc. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 19 View(s) Cont..  By default, Views are available inside the Views folder at the root.  Usually, views are grouped into folder names with the applications controller.  Each controller will have its own folder in which the controller-specific view files are going to be stored.  The controller-specific folders are going to be created within the Views folder only.  View file name may be the same as the action method name of a controller. (if it differs then you need to specify the view name) Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 20 View(s): Example  Let’s say, we have an ASP.NET Core MVC application with two controllers  i.e. HomeController and StudentController.  The HomeController is created with the following three action methods.  AboutUs()  ContactUs()  Index()  On the other hand, the StudentController is created with the following four action methods.  Index()  Details()  Edit()  Delete() Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 21 Controller  A Controller is a special class in ASP.NET Core Application with.cs (for C# language) extension.  By default, when you create a new ASP.NET Core Application using Model View Controller (MVC) template, then you can see the Controllers are residing in the Controllers folder.  In ASP.NET Core MVC Application, the controller class should and must be inherited from the Controller base class.  The Controllers in the MVC application logically group similar types of actions together.  This aggregation of actions or grouping of similar types of action together allows us to define sets of rules such as caching, routing, and authorization which are going to be applied collectively. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 22 Controller Cont..  When the client (browser) sends a request to the server, then that request first goes through the request processing pipeline.  Once the request passes the request processing pipeline, it will hit the controller.  Inside the controller, there are lots of methods (called action methods) actually handle that incoming HTTP Requests.  The action method inside the controller executes the business logic and prepared the response which is sent back to the client who initially made the request. (See below image) Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 23 Adding Controller in ASP.NET Core Project  Right-click on the Controller folder and select the Add => Controller option from the context menu which will open the Add Controller window as shown in the below image.  Here, we are going to create the MVC Controller with the Empty template. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 24 Controller Cont.. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 25 Controller Cont.. Role of Controller in MVC  A Controller is used to group actions i.e. Action Methods.  The Controller is responsible to handle the incoming HTTP Request & Response.  The Mapping of the HTTP Request is done using Routing & that is for a given HTTP Request, which action method of which controller is going to invoke is handled by the Routing Engine.  Many important features such as Caching, Routing, Security, etc. can be applied to the controller.  Attributes also can be applied at the Controller level i.e Routing Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 26 Model  A model is a class that contains the business logic of the application.  It also used for accessing data from the database.  The model class does not handle directly input from the browser.  It does not contain any HTML code as well.  Models are also refers as objects that are used to implement conceptual logic for the application.  A controller interacts with the model, access the data, perform the logic and pass that data to the view.  It represents a set of classes that describes the business logic and data.  By default, models are stored in the Models folder of the project.  In short, model represents a set of classes that are used to describe the application’s validation logic, business logic, and data access logic. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 27 Model Example To Add Model In Project Right Click on Models Folder  Add  Class Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 28 Summary - MVC Architecture Pattern  Model  View  Controller  The model represents the  The view is a visual  The Controller receives the data that needs to be shown representation of the model. request. to the user and some  Responsible for interacting  Process incoming requests associated logic. with the User. from the user.  It is an object or just another  Render the model to the user.  Passes the validations and c# class with properties and errors back to View if any. methods.  Accept User interaction and pass it to controller.  The controller acts on both  The model does not and side model and view. should not depend on  Consists of Standard HTML Controller or View. Pages / JavaScript and CSS.  Controllers are the  Should be able to Render components that manage  The only responsibility of the user input, interact with the model is to hold the data. The JSON, XML and custom return types. model, and choose which model class is ideally view to render. reusable. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 29 ASP.Net Core Life Cycle Section – 2.4 ASP.Net Core Life Cycle  Application Start  Controller Initialization  The program.cs class is executed when the  The selected controller is instantiated, and its application starts. dependencies are injected.  This class configures services and the  Action Method Execution request pipeline.  The action method of the controller is  Middleware Pipeline executed.  Middleware components are executed in the  This method processes the request and order they are added to the pipeline. prepares the response.  Each middleware can handle requests and  Result Execution responses, and decide whether to pass the request to the next middleware.  The result from the action method (e.g., a view, JSON data) is executed.  Routing  If it’s a view, the view engine renders the  The routing middleware matches the incoming HTML. request to a route.  Response  It determines which controller and action method should handle the request.  The final response is sent back to the client. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 31 Action & Non Action Methods Section – 2.5 Action Methods Home Controller Class Base Controller Class Return Type Action Method View() UI defined in base Controller class Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 33 Action Methods Cont..  Action methods are responsible for handling HTTP requests and returning HTTP responses.  They are the methods that perform specific actions in response to user requests.  These methods are typically associated with URLs and are used to execute specific functionality based on the request type (e.g., GET, POST, PUT, DELETE).  Action methods are public and typically return an ActionResult or one of its derived types (e.g., ViewResult, JsonResult, RedirectToActionResult) to determine the response to send back to the client.  Let’s see example of an action method in a controller: Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 34 Non-Action Methods  Non-action methods are regular methods in a controller that are not intended to be used as entry points for handling HTTP requests.  They are auxiliary methods used to factor out common functionality or logic to be shared among action methods.  Non-action methods are typically marked with the [NonAction] attribute to explicitly indicate that they should not be invoked as actions.  These methods cannot be directly accessed via a URL, and they do not return ActionResults.  Let’s see example of an action method in a controller: Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 35 IActionResult Object Section – 2.6 IActionResult Object | Return Types  These include various result types derived from ActionResult,  ViewResult  JsonResult  ContentResult  StatusCodeResult  FileResult  RedirectResult Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 37 1. ViewResult Object  The View method creates a ViewResult object by defining a model which will be transferred to the View.  Represents an HTML view template that should be rendered and returned as a response.  Typically used for rendering HTML pages to be displayed in a web browser.  The View() method has 4 different overloaded versions which are described in the below table: Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 38 1. ViewResult Object Cont.. Method Description View() Targets the default View to render it. E.g. if the action method name is List and you are using the View() method (with empty parameter) then the List.cshtml view will be rendered. View("ViewName") This version takes the view name in it’s parameter and this view will be rendered. E.g. if you use View("Show") then the show.cshtml view will be rendered. View(model) This version will render the default view by providing it with model data (class object). This is used to make the rendered view strongly typed. View("ViewName", model) This version specifies the View by it’s name along with the model data that it will be provided with. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 39 2. JsonResult Object  JsonResult represents an HTTP response containing JSON data (i.e., key-value pairs).  It is used when we want to return JSON-formatted data from a controller action method to the client.  JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate.  When we return a JsonResult from a controller action, ASP.NET Core MVC serializes the specified data into JSON format and sends it back to the client as the HTTP response body.  This is commonly used for AJAX requests where the client-side JavaScript code expects to receive data in JSON format or when building APIs. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 40 2. JsonResult Object Cont.. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 41 3. ContentResult Object  It is a type of ActionResult that returns a string or binary content to the client.  It's commonly used for returning files, images, or other types of content.  Here are some key properties and methods of the ContentResult object:  Content: The content to be returned to the client.  ContentType: The MIME type of the content.  StatusCode: The HTTP status code to be returned with the content.  You can use ContentResult to return different types of content, such as:-  Text: return Content("Hello, World!", "text/plain")  Image: return Content(imageBytes, "image/jpeg")  File: return Content(fileBytes, "application/octet-stream", fileName) Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 42 4. StatusCodeResult Object  Represents an HTTP status code without a specific content response.  Used for returning HTTP status codes like 404 (Not Found), 500 (Internal Server Error), etc. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 43 5. FileResult Object  The FileResult class is used to return files from a controller action.  It is an action result that represents a file to be returned to the client for download or display.  This is the parent class of all file-related action results.  It’s a base class used to send binary file content to the response.  When executed, it writes a file as the response.  This can be useful for scenarios where you need to send a file to the client, such as downloading a document, image, or any other type of file. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 44 6. RedirectResult  The RedirectResult class in ASP.NET MVC Core is an ActionResult used to instruct the user's browser to navigate to a different URL.  It's a handy tool for managing the flow of your web application, especially in scenarios like:  After form submissions: Redirect the user to a confirmation page or a success message.  Login operations: Redirect to the main dashboard after successful login.  Conditional navigation: Based on user roles or actions, redirect them to specific pages.  External URLs: Redirect to external sites for authentication or other purposes.  It sends an HTTP status code of 302 (Found) by default, which tells the browser to perform a temporary redirect to the specified URL. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 45 RedirectToAction  RedirectToAction method is used to redirect users from one action method to another within the same or different controller.  It’s commonly used for navigation and routing purposes.  The RedirectToAction method sends an HTTP status code of 302 (Found) by default, instructing the browser to perform a temporary redirect to the specified action.  You can also specify a permanent redirect by sending a 301 status code, which performs a standard HTTP redirection.  Here’s an example of using RedirectToAction to redirect from the current action to another action within the same controller: Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 46 RedirectToAction Cont..  Redirecting to a Different Controller  If you want to redirect to an action in a different controller, you can specify both the controller name and the action name:  Passing Route Values  You can also pass route values (parameters) to the target action. For example, redirecting to an action with an id parameter Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 47 Action Verbs Section – 2.7 Action Verbs  The ActionVerbs selector is to handle different type of Http requests.  The MVC framework includes HttpGet, HttpPost, HttpPut, HttpDelete and HttpPatch action verbs.  You can also apply one or more action verbs to an action method to handle different HTTP requests.  If you don't apply any action verbs to an action method, then it will handle HttpGet request by default.  APIs are increasingly using action verbs.  Selectors like this are used to ensure that the Action method is controlled based on the HTTP method. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 49 Action Verbs Cont.. You can also apply multiple action verbs using the AcceptVerbs attribute, as shown below. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 50 Passing Data Section – 2.8 Passing Data  The following are the scenarios where we can use these objects.  Pass the data from Controller to View.  Pass the data from one action to another action in the same Controller.  Pass the data in between different Controllers. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 52 ViewBag  ViewBag is lightweight method of transferring values to Controllers to Views.  ViewBag only transfers data from action methods to views, not visa-versa.  ViewBag values are lost if redirection occurs in the action method.  Once the ViewBag values are read, DOTNET will remove it from the memory. This means to reuse these values you will have to store them in some variables. HomeController.cs 1 public IActionResult Index() 2 { 3 ViewBag.Title = "Welcome"; 4 return View(); 5 } Index.cshtml 1 @ViewBag.Title Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 53 ViewData  ViewData is a dictionary object to pass the data from Controller to View where data is passed in the form of key-value pair.  Typecasting is required to read the data in View if the data is complex and we need to ensure null check to avoid null exceptions.  The scope of ViewData is similar to ViewBag and it is restricted to the current request and the value of ViewData will become null while redirecting. HomeController.cs 1 public IActionResult Index() 2 { 3 ViewData["Title"] = "Welcome"; 4 return View(); 5 } Index.cshtml 1 @ViewData["Title"] Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 54 TempData  TempData is a dictionary object to pass the data from one action to other action in the same Controller or different Controllers.  Tempdata is also required to typecast and for null checking before reading data from it.  TempData scope is limited to the next request and if we want Tempdata to be available even further, we should use keep() and peek(). HomeController.cs Index.cshtml 1 public IActionResult Index() 1 @TempData["Data"] 2 { 3 TempData["Data"] = "I am from Index action"; 4 return View(); 5 } 6 7 public string Get() 8 { 9 return (string)TempData["Data"]; 10 } Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 55 Summary | Passing Data  MVC automatically removes the values of the TempData as soon as they are read.  There is ‘Keep’ method to prevent MVC from removing the value once read.  However if the value is read again (2nd time) then MVC will delete it.  The ‘Peek’ method allows you to get the value and also prevent it from deletion.  This is because it does not tells MVC that the value has been read.  We may Use session to store the value permanently (until the session expires) for as many reads as you want and in any part of the application. Prof. Naimish R. Vadodariya #2305CS311 (Web Programming using.NET)  Unit 2 – Introduction to ASP.NET Core 56 Web Programming using.NET #2305CS311 Thank You Prof. Naimish R. Vadodariya Computer Science & Engineering Department Darshan University, Rajkot [email protected] 8866215253

Use Quizgecko on...
Browser
Browser