0% found this document useful (0 votes)
1 views

7_lecture 3 - Getting Started With ASP Net Core

This document serves as a comprehensive guide to getting started with ASP.NET Core, covering its features, project structure, and the Model-View-Controller (MVC) architecture. It includes practical demonstrations on building web applications, utilizing Razor syntax, and implementing data passing techniques. Key topics also include action methods, result types, and form handling in ASP.NET Core.

Uploaded by

sonbim1999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

7_lecture 3 - Getting Started With ASP Net Core

This document serves as a comprehensive guide to getting started with ASP.NET Core, covering its features, project structure, and the Model-View-Controller (MVC) architecture. It includes practical demonstrations on building web applications, utilizing Razor syntax, and implementing data passing techniques. Key topics also include action methods, result types, and form handling in ASP.NET Core.

Uploaded by

sonbim1999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

GETTING STARTED WITH ASP.

NET CORE
Learning Objectives

• Introduction to cross-platform, high-performance framework.


• Hands-on experience in creating web applications with ASP .NET
Core.
• Topics covered: Configuration, middleware, routing, and controllers.
INTRODUCTION TO ASP.NET CORE

• It’s a unified framework for building web UI and web APIs.


• It has built-in dependency injection.
• Despite being built on a new web stack, it has a high degree of
compatibility with ASP.NET.
• ASP.NET Core is also perfectly suited for Docker containers.
• It has built-in support for SPA with client-side frameworks like
Angular, React, Vue.
INTRODUCTION TO ASP.NET CORE
FEATURES OF ASP NET CORE
1.Cross-platform support
for versatile deployment.
2.Emphasis on high
performance for robust
and scalable applications.
3.Reduced code writing due
to implemented shared
libraries.
4.Easy maintenance of web
applications.
5.Cloud-based application
development support,
including Dockerization for
deployment.
ASP.NET CORE PROJECT FOLDER STRUCTURE

• The solution explorer displays all the


projects related to a single solution.
• The project folder structure is organized
hierarchically, with each level representing a
different aspect of the application.
.csproj file

1.Since ASP.Net Core 2.0, Visual Studio utilizes .csproj for project management.
2.Double-clicking on .csproj enables property settings adjustment.
3.Allows changes to target framework and other implicit settings in the project SDK.
FOLDER STRUCTURE
launchSettings.json

• launchSettings.json:
• Includes visible setting profiles and debug settings.
• Profiles cover details like iOS settings, application port number, and environment (development/production).
• Essential configuration for launching and debugging ASP.NET Core applications.
• Ensures flexibility in managing settings based on profiles and deployment environments.
wwwroot
• wwwroot Folder:
• wwwroot Folder.
• Houses static files (CSS, JavaScript, Bootstrap,
libraries, images) for use in applications.
• Serves as a centralized location for managing
and accessing static resources.
Pages
• Pages Folder:
• Contains sample pages.
• Default Pages:
• Automatically run when the application is
executed.
• Referred to as reserve pages.
• Provide a starting point for understanding and
exploring ASP.NET Core application structure.
DEMO:
BUILDING A
WEB
APPLICATION
13
14
15
MODEL-VIEW-CONTROLLER
COMMUNICATION •Request Handling:
•User request is received by the controller.
•Controller determines whether to communicate with the
view for rendering or with the model for data preparation.
•Controller Actions:
•If rendering is required, the controller interacts with the
view using return view in the action method.
•If data preparation is needed, the controller
communicates with the model or database, prepares the
data, and then sends it to the view.
•Interaction Dynamics:
•View and controller do not directly interact.
•Controller acts as a middle iterator or binder between the
view and the model.
•User Response:
•Controller responds back to the browser, providing the
final output expected by the user.
MODEL-VIEW-CONTROLLER
COMMUNICATION
• Model to Model Communication:
• This is achieved via parameters/composition.
• Model to View Communication:
• This follows a specific path: Model > Controller > View.
• Direct movement from model to view isn’t possible.
• The process involves creating a model object in the controller before passing
it on to the view.
• The steps for passing data or communicating from model to view are:
o Taking the object in the action of a controller.
o Passing the model object as a parameter to view.
o Using @model to include the model on the view page.
MODEL-VIEW-CONTROLLER
COMMUNICATION
• Model to Controller Communication:
• This involves creating an object of the Model class in Controller to access the
Model in Controller.
• View to Model Communication:
• This follows a specific path: View > Controller > Model, indicating that direct
movement from View to Model is not possible.
• Data must be submitted first to the controller before passing it on to the
model.
• The steps for this communication are:
o Submitting an HTML form to a Controller.
o Creating an object of Model in Controller.
o Passing values to the Model object.
MODEL-VIEW-CONTROLLER
COMMUNICATION
• View to View Communication:
• We can move from one view to another view by using partial views.
• View to Controller Communication:
• We can move data from view to controller by submitting forms to controllers
or by:
o JSON
o AJAX Calls
o JavaScript
o Partial Views
MODEL-VIEW-CONTROLLER
COMMUNICATION
• Controller to Model Communication:
• We can move from Controller to Model just like we move from Model to
Controller.
• View to Controller Communication:
• We can move data from controller to view in the following ways:
o By using viewBag
o ViewData
o TempData
• Controller to Controller Communication:
• We can move from one Controller to another by using RedirectToAction(), and
then pass the name of the specific action.
DEMO:
HANDLING
REQUESTS IN
.NET MVC CORE
22
23
ACTION
METHODS AND
RESULT TYPES
ACTION METHODS

• An action is a method that responds to user action/activity.


• Any method in a controller which has public access modifier acts as
an action method.
• They are like any other normal methods with the following
restrictions:
• Action method must be public. It cannot be private or protected.
• Action method cannot be overloaded.
• Action method cannot be a static method.
ACTION METHODS

• Every controller can have default action method as per configured


route in the RouteConfig.
• By default, the Index() method is a default action method for any
controller.
• Also, you can change the default action name as per your
requirement in the RouteConfig class.
ACTION METHODS
28
29
30
ACTION RESULT

• The MVC Framework includes various Result classes, which can be


returned from an action method.
• Result classes represent different types of responses, such as HTML, file,
string, JSON etc.
• The ActionResult class is a base class of all the above result classes, so it
can be the return type of an action method that returns any result.
• You can specify the appropriate result class as a return type of an action
method.
• The base controller class includes the View() method along with other
methods that return a particular types of result.
ACTION RESULT

Request goes to the particular Action Result and the type of data
that action method result returns that View is being rendered based
upon the result set.
ACTION RESULT
Result Class Description Base Controller Method

ViewResult Represents HTML and markup. View()

EmptyResult Represents No response. Content()


ContentResult Result string literal. Content()
FileContentResult Represents the content of a file. File()

RedirectResult Represents a redirection to a new URL. Redirect()

JsonResult Represent JSON that can be used in AJAX. Json()

PartialViewResult Returns HTML from Partial view. PartialView()

JavaScriptResult Represents a JavaScript script. JavaScript()

HttpUnauthorizedResult Represents HTTP 403 response.


RAZOR VIEW
ENGINE AND
RAZOR SYNTAX
RAZOR VIEW ENGINE

• The Razor View Engine is the default View Engine for the ASP.NET
Core apps.
• It looks for Razor markup in the View File and parses it and produces
the HTML response.
• It is used to generate views that are returned to the client’s browser
in response to a request.
• It is a powerful and flexible templating engine.
• With this, it is easier to create dynamic web pages in ASP.NET Core.
• It enables developers to write clean and maintainable code that can
be easily understood.
RAZOR VIEW ENGINE
• RazorView engine
integrates HTML markup
tags with C# code.
• C# code is sent to the
View Engine.
• View Engine parses the
request into pure HTML.
• The resulting HTML is
then displayed in the
browser.
RAZOR VIEW ENGINE

• Razor is a markup syntax for embedding .NET based code into


webpages.
• The Razor syntax consists of Razor markup, C#, and HTML.
• Files containing Razor generally have a .cshtml file extension.
• Razor syntax is similar to the templating engines of various JavaScript
single-page application (SPA) frameworks, such as Angular, React etc.
• Razor supports C# and uses the @ symbol to transition from HTML to
C#.
•<p>@Model.Username </p> by a Razor reserved keyword, it
When an @ symbol is followed
indicates specific functionality or behavior in the code.
DEMO: RAZOR VIEW ENGINE

38
DEMO: RAZOR VIEW ENGINE

39
DEMO: RAZOR VIEW ENGINE

40
DEMO: RAZOR VIEW ENGINE

41
Customer.cs
DEMO: RAZOR VIEW ENGINE

43
DEMO: RAZOR VIEW ENGINE

44
LAYOUT,
SECTIONS AND
VIEWSTART
LAYOUT VIEW

• Layouts resemble master pages


• Define consistent structure for multiple views
• Include elements like headers, footers, and navigation menus
• Promote content reusability across various pages
• Facilitate HTML structure definition with content placeholders
USE OF LAYOUT VIEW
• Web Application
Structure:
• Website Header
• Website Footer
• Navigation Menus
• Main Content Area
• Organizational Advice:
• Use a layout view to
organize these common
sections.
• Inherit this layout view
in each page for a
consistent look and
feel.
DEMO: LAYOUT VIEW
DEMO: LAYOUT VIEW
DEMO: LAYOUT VIEW
• Utilize "RenderBody" in the view
(e.g., Details.cshtml)
• This function integrates specific
code into the layout
• The rest of the layout remains
consistent
• "RenderBody" precisely renders
content added in Details.cshtml
HTML HELPER
AND TAG
HELPER
HTML HELPER

• Renders HTML controls in the razor view.


• Binds model object to HTML controls to display value of model
properties.
• Assigns the value of the controls to the model properties while
submitting a web form.
• Always use the HtmlHelper class in razor view instead of writing
HTML tags manually.
• The HtmlHelper method is designed to make it easy to bind to view
data or model data.
DEMO: HTML HELPER
• Utilize ActionLink for navigation
• First parameter: Text visible for
navigation link (Details page)
• Second parameter: Name of the
action method (Details in the
Customer controller)
• Third parameter: Name of the
controller
DEMO: HTML HELPER
• Clicking on the Details page
navigates to the Details method in
the Customer controller.
TAG HELPER
TAG HELPER

• A new feature that enables server-side code to create and render


HTML elements in Razor View.
• It is a feature of the Razor View engine.
• Tag Helper involves C# classes in view generation by creating HTML
elements.
• It can change the content of HTML element and add additional
attributes to HTML element.
• Tag Helper is very similar to HTML helper in ASP.NET MVC, making it
easier to bind to view data or model data.
TAG HELPER

• HTML HELPER:

• EQUIVALENT WITH TAG HELPER

• EQUIVALENT HTML
DEMO: TAG HELPER
ROUTING
ATTRIBUTE ROUTING

• Technique used for defining routes directly in the controller code


using attributes.
• Developers can specify the URL pattern for a particular action method
using attributes.
• The [Route] attribute is used to specify the URL pattern for an action
method.
• By specifying the route directly in the controller code, developers can
have fine-grained control over the URL patterns for each action
method.
ATTRIBUTE ROUTING

• Consider the following code

• In this example, the [Route] attribute specifies that the GetProduct


method should be invoked for URLs in the format of /products/{id}
DEMO: ATTIRBUTING ROUTING
DATA PASSING
TECHNIQUES
DATA PASSING TECHNIQUES
• The following are the object which store value and transfer it from on place to other place

ViewData and ViewBag: Cookies: Session:


Temporary storage during a single request-response Can be persistent or non-persistent. Enables data storage throughout the application
cycle. Choice depends on the desired data storage lifecycle.
Limited to the current request, data may be lost duration. Persists until explicitly removed.
afterward. QueryString:
TempData: Data travels between requests in the form of a URL.
Data persistence for more than one request. Useful for passing data through URLs.
Retention facilitated through the "Keep" method.
VIEWBAG

• Used to transfer temporary data not included in the model from the
controller to the view.
• It is a dynamic type property of the ControllerBase class, which is the
base class of the Controller class.
• It is often used for simple scenarios where a strongly typed model is
not required.
DEMO: VIEWBAG
DEMO: VIEW BAG
VIEWDATA

• Used to pass data from the controller action method to a view. This
data can be displayed on the view.
• Works on the principle of Key-value pairs.
• This type of binding is known as loosely binding.
• Can pass any type of data like normal integer, string, and even
objects.
• ViewData only transfers data from controller to view, not vice-versa. It
is valid only during the current request.
DEMO: VIEWDATA
ASP.NET CORE
FORMS
ASP.NET CORE FORM

• Key part of building web applications using the ASP.NET Core framework.
• Allow users to submit data to a server.
• Can be used to create, update, or delete records, or to perform some other
action.
• Can be created using HTML helpers, which are methods that generate
HTML code to display and interact with forms.
• When a user submits a form, the data is typically sent to the server using a
POST request.
• The server then receives the data and can use it to perform the desired
action, such as updating a database record.
ASP.NET FORM
WEAKLY-TYPED FORMS STRONGLY-TYPED FORM
• Technique where data is not explicitly bound to a specific data model.
• Explicit Data Binding:
• Form data is accessed as a collection of key-value pairs.
• Data tied explicitly to a specific data model.
• Keys represent the names of form fields and values represent user input.

• Developers can access this using the Request object. • Data Model Definition:
• Allows developers to read and manipulate form data directly without needing to create a specific data model. • Developers create a data model mirroring form data structure.
• Model Binding Process:
• Automates mapping form data to data model.
• Structured Data Models:
• Classes/structures define form field properties and data types.
• Automatic Mapping:
• Form data mapped automatically to data model properties.
• Compile-Time Validation:
• Occurs during compile-time for early error detection.
• Reduced Runtime Errors:
• Model binding minimizes the risk of runtime errors.
DEMO: WEAKLY-TYPED FORM
DEMO: WEAKLY-TYPED FORM
DEMO: WEAKLY-TYPED FORM
DEMO: WEAKLY-TYPED FORM
DEMO: STRONGLY-TYPED FORM
DEMO: STRONGLY-TYPED FORM
DEMO: STRONGLY-TYPED FORM
DEMO: STRONGLY-TYPED FORM
MODEL BINDING
MODEL BINDING

•Mechanism in ASP.NET Core:


•Extracts data from an HTTP request and provides them to the controller action
method parameters.
•Action Method Parameters:
•Can be simple types (e.g., integers, strings) or complex types (e.g., Student, Order,
Product).
•Automatic Data Mapping:
•ASP.NET Core automatically maps data from the request to action method parameters
using model binding.
•Powerful Feature:
•Model binding is a powerful feature simplifying code and reducing boilerplate in
ASP.NET Core applications.
MODEL BINDING

• For example, let’s say you have an action method that takes a Person
object as a parameter

• When the client submits a form that includes data for a Person object
DEMO: MODEL BINDING
DEMO: MODEL BINDING
DEMO: HANDLING
FORMS POST
Q&A

You might also like