Unit 3
Unit 3
Using Asp.Net
Unit-3
Installing Asp.Net and Web Development
Steps
Start Visual Studio and select Create a new project.
In the Create a new project dialog, select ASP.NET Core Web App (Model-
View-Controller) > Next.
In the Configure your new project dialog, enter MvcMovie for Project name.
It's important to name the project MvcMovie. Capitalization needs to match
each namespace when code is copied.
Select Next.
In the Additional information dialog:
Select .NET 8.0 (Long Term Support).
Verify that Do not use top-level statements is unchecked.
Select Create.
What is MVC?
MVC-based apps contain:
Models: Classes that represent the data of the app. The model classes use validation logic to enforce
business rules for that data. Typically, model objects retrieve and store model state in a database. In this
tutorial, a Movie model retrieves movie data from a database, provides it to the view or updates it. Updated
data is written to a database.
Views: Views are the components that display the app's user interface (UI). Generally, this UI displays the
model data.
Controllers: Classes that:
Handle browser requests.
Retrieve model data.
Call view templates that return a response.
Working of a MVC
User Interaction: A user interacts with the application by making a request to a URL, such as clicking a link
or submitting a form.
Routing: The ASP.NET MVC routing system maps the incoming URL to a specific controller action method
based on the route configuration defined in the application.
Controller Processing: The controller action method receives the request, performs any necessary processing
(such as retrieving data from the database), and prepares the data to be displayed.
View Rendering: The controller action method selects an appropriate view to render and passes the data to
the view.
HTML Generation: The view generates HTML dynamically based on the data provided by the controller and
renders it to the user's browser.
User Interaction (Again): The user sees the rendered HTML in their browser and interacts with the
application (e.g., clicking links, submitting forms).
MVC?
MVC is Model, View, and Controller framework.
Model is the business layer of an application. It contains classes and application logic.
View is the front-end or interface through which a user interacts with our application.
Controller is the bridge between Model and View. It is used to handle requests.
Communications
Model to Model
We can communicate from Model to Model via parameters / composition.
Model to View
To communicate form Model to View, you have to follow the path: Model >
Controller > View
We can’t directly move from Model to View. First, the Model object is made in the
Controller and then it is passed to View. We can pass the data or communicate from Model
to View by these three steps:
Take the object in the action of a Controller.
Pass Model object as a parameter to View.
Use @model to include Model on the View page.
Model to Controller
View to Model
To communicate from View to Model, you have to follow the path: View > Controller >
Model
You can’t directly move from View to Model. First, you have to submit data to the Controller and then pass it to
Model. To pass the data from View to Model, you have to follow these three steps:
View to Controller
We can move data from View to Controller by submitting forms from View to specific Controller or by -
JSON
AJAX Calls
JavaScript
Partial Views
Controller to Model
We can move from Controller to Model just like we move from Model to Controller - by creating an object of Model
in Controller.
Controller to View
By using ViewBag
ViewData
TempData
Controller to Controller
We can move from one Controller to another by using RedirectToAction(); and then pass the name of the specific action.
View to view
Razor is a templating engine and ASP.NET MVC has implemented a view engine which allows us to use Razor inside of an
MVC application to produce HTML. However, Razor does not have any ties with ASP.NET MVC.
Now, Razor Syntax is compact which minimizes the characters to be used, however it is also easy to learn.
Some of Razor Syntax Rules for C# are given below.
It starts with code block and its condition is written in parenthesis. And the code which needs to be executed once condition
gets satisfied is written inside braces.
● @{var price=60;}
● <html>
● <body>
● @if (price>50)
● {
● <p>The price is greater than 50.</p>
● }
● </body>
● </html>
If – Else statement
It starts with code block and its condition is written in parenthesis. And code which needs to be executed once the condition gets satisfied is written inside braces and
if it does not gets satisfied then code written inside else block gets executed.
● @{var price=60;}
● <html>
● <body>
● @if (price>50)
● {
● <p>The price is greater than 50.</p>
● }
●
● else
● {
● <p>The price is less than 50.</p>
● }
●
● </body>
● </html>
How To Create a Controller in Asp.net MVC?
To create a controller in an ASP.NET MVC application, you typically follow these steps:
Launch Visual Studio, and either create a new ASP.NET MVC project or open an existing one.
Add a Controller:
Right-click on the "Controllers" folder within your project in the Solution Explorer. Then, choose "Add" ->
"Controller".
In the "Add Scaffold" dialog that appears, select "MVC Controller with views, using Entity Framework" or
"MVC Controller" depending on your requirements.
Controller Creation
Create Corresponding Views
To create corresponding views for the actions in the controller, follow these steps:
Index View:
● Right-click within the Index() action method in the controller.
● Select "Add View".
● In the "Add View" dialog, provide a name for the view (e.g., "Index").
● Choose the template for your view. For the Index() action, you might select "Empty" or "List".
● Click "Add".
About View:
● Right-click within the About() action method in the controller.
● Select "Add View".
● Provide a name for the view (e.g., "About").
● Choose the template as per your requirements.
● Click "Add".
Contact View:
● Right-click within the Contact() action method in the controller.
● Select "Add View".
● Provide a name for the view (e.g., "Contact").
● Choose the template.
● Click "Add".
Layout,Sections and ViewStart
Shared Structure: A layout typically contains the HTML structure that is common across multiple
pages of your website. This includes elements like the header, footer, navigation menus, and
other common sections.
Content Placeholder: Within the layout, you define one or more content placeholders using the
@RenderBody() directive (in Razor syntax). These placeholders indicate where the content of
individual views should be inserted.
Consistent Appearance: By using a layout, you ensure that all pages in your application have a
consistent appearance and structure. Any changes made to the layout are automatically reflected
across all pages that use that layout.
Flexible Design: Layouts can also include additional placeholders for sections that may vary from
page to page, such as a sidebar or a section for dynamic content. Views can then optionally
override these sections as needed.
Creation of the Layout
1. First of all, You have to create a controller- I have created a controller named “HomeController1.cs”.
2. Create three methods named as Index,About and Contact.
3. Then create the corresponding views.
4. In Index.cshtml, write some content in h1 or paragraph tag.
5. In Contact.cshtml, write some content in h1 or paragraph tag.
6. In About.cshtml, write some content in h1 or paragraph tag.
7. We are using Layout, as we want a layout must be created once and it will be common for every
action and their corresponding view
Creation of Action Methods and also create views of action methods
Now, you have to create Layout file
Go inside views/shared and Right click on shared
Now _Layout1.cshtml file has been created
Write something above and below @RenderBody
Now you have to link your layout file to all action methods
Right click on _Layout1.cshtml file, then you will be able to see the copy full path option. Copy that path
Paste that path in Index/about/contact view
Layout=”~/Views/Shared/_Layout1.cshtml”
Make sure you have to use / instead of \. So corrected version is in the next slide
HTML TAG HELPERS
In MVC, developers normally do not use any web content for their applications.
Because, Microsoft introduced three helper objects (HtmlHelper, UrlHelper, and
AjaxHelper) for generating web control in the application. These helper objects
simply shorten the work of the developer for designing any application of web
interface. In the MVC pattern, all the code of Razor views (including server-side)
starts with the @ sign. In this way, the MVC framework always has a clear separation
between the server-side code and client-side code.
Why Tag Helpers?
Microsoft introduced a new feature in the MVC Razor engine with the release of ASP.NET Core which is
known as Tag Helpers. This feature helps web developers use their old conventional HTML tags in their web
applications for designing presentation layers.
So, with the help of Tag Helpers, developers can replace the Razor cryptic syntax with the @ symbol, a more
natural-looking HTML-like syntax. So, the first question always arises “Why do we need Tag Helpers?”.
The simple answer is that Tag Helpers reduce the coding amount in HTML which we need to write and also
create an abstracted layer between our UI and server-side code. We can extend the existing HTML tag
elements or create custom elements just like HTML elements with the help of Tag Helpers.
Difference between HTML helpers and Tag Helpers
// HTML Helpers
//Tag Helpers
The following are the scenarios where we can use these objects.
ViewBag is a dynamic object to passes the data from the Controller to View. This will pass the data as a property of the
object ViewBag. And we have no need to typecast to read the data or for null checking.
In controller
ViewBag.Title = “Welcome”;
return View();
}
In view
Example View
<h2>@ViewBag.Title</h2>
What is ViewData?
ViewData is a dictionary object to pass the data from Controller to View, where data is passed in the form of a key-value pair.
Typecasting is required to read the data in View if the data is complex, and we need to ensure a 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.
Example Controller
C#Copy
Example View
<h2>@ViewData[“Title”]</h2>
What is TempData?What is TempData?
TempData is a dictionary object to passes the data from one action to another action in the same Controller or different
Controllers. Usually, the TempData object will be stored in a session object. 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.
Example Controller
builder.Services.AddSession(options =>
options.IdleTimeout = TimeSpan.FromSeconds(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
Explanation
[HttpPost]
public ActionResult Action()
{
string username = Request.Form["username"];
string password = Request.Form["password"];