0% found this document useful (0 votes)
1 views15 pages

MVC-Chapter2

Chapter 2 discusses the MVC (Model-View-Controller) architecture in ASP.NET, detailing the roles of Models, Views, and Controllers in web applications. It explains how to create controllers and action methods, invoke them via URLs, and pass parameters, as well as the use of ViewData and ViewBag for data transfer to views. Additionally, it covers routing mechanisms, Razor syntax for views, and the use of partial views for code reuse.

Uploaded by

vijaya2511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views15 pages

MVC-Chapter2

Chapter 2 discusses the MVC (Model-View-Controller) architecture in ASP.NET, detailing the roles of Models, Views, and Controllers in web applications. It explains how to create controllers and action methods, invoke them via URLs, and pass parameters, as well as the use of ViewData and ViewBag for data transfer to views. Additionally, it covers routing mechanisms, Razor syntax for views, and the use of partial views for code reuse.

Uploaded by

vijaya2511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Chapter 2:

----------
Working with Controllers and Views:

Model refers to the set of classes that describes the data that the
application works with.
View is a combination of HTML mark up and code that runs on the web
server .
Controller refers to the set of classes that handle communication from
the user and overall application flow.
MVC provides a Scaffolding technique feature that provides a quick
way to generate code automatically for common used operations
Bundling is a technique provided by ASP.NET MVC that allows you to
combine multiple files such as CSS and JS
The mechanism to locate an appropriate action method for a given URL
is called Routing. In ASP MVC routing has 2 purposes.
It maps the URLs of the incoming requests with controller actions.
It builds outgoing URLs that correspond to controller actions.
Controller:
-- Process incoming request.
-- Executes the appropriate code initiated or required by the user
-- Communicating with the "Model" to validate and process the data.
-- Rendering the required view.
---Handles all incoming requests.
---Controllers are implemented in MVC application as C# classes
inherited from System.Web.Mvc.Controller class
Controller - is a class...
it is .cs code [C# file], which is inherited by a built-in Controller classes.
Create the class (.cs file) in the folder Controller.
public class HomeController : Controller
{
//code
}
Note: the name of the controller should be suffixed with Controller
keyword. - Naming convention.
Inside controller, we can create action methods.
These action methods are public methods that will be invoked in
response to the user actions.
public class HomeController : Controller
{
public ActionResult Index()
{
//code
}
}

After the controller is created, how to invoke?


-- We can invoke controllers , by specifying a URL in the browser.
http://localhost/Controller/ActionMethod
eg: http://localhost:77701/ Home/Index
Example 2:
public class EmployeeController : Controller
{
public ActionResult Accept()
{
//code
}
}
To Invoke:
eg: http://localhost:77701/ Employee/Accept

Note: The method name can be anything, but return type of the method
should be ActionResult which is an instance of
System.Web.Mvc.ActionResult class.
Most Action methods return ActionResult instance but other return types
like int, string or bool also can be used.
public class HomeController : Controller
{
public string Index()
{
Return “Home controller Index method”;
}
}
http://localhost:1078/Home/Index
Example 2:
public string Display()
{
return "From display";
}
To invoke
http://localhost:1078/Home/display
(localhost:1078 is automatically generated by your computer. It will vary
everytime.)
Passing Parameters in Controller Actions
QueryStrings --- is a part of a URL. It is is used to pass data to web
servers and starts with ?ParamterName=Value
http://localhost:77701/ Home/Browse?Category=Soap
In the above url, Browse is the Action method and Category is the
parameter. So our Action method will be
public string Browse(string Category)
{
return ("Category is " + Category);
}

To invoke
http://localhost:1078/Home/Browse?category=mvc

Integer return
public int BrowseInt(int Category)
{
return (Category);
}

http://localhost:1078/Home/BrowseInt?Category=8
output : 8
For passing multiple parameters
public string DisplayNew(string cat,int pno)
{
return "Category is "+ cat + " pno is " + pno.ToString();
}
To Invoke
http://localhost:1078/Home/DisplayNew?cat=try&&pno=7
output: Category is try pno is 7

Minification removes unnecssry white space and comments from the


Javascript or CSS code and shortens variable names.
Working with Views:
-- used to display the User interface on the applications
-- Combination of HTML mark up code and code that runs on the web
server
-- View codes are embedded using Razor syntax
-- A web application can have multiple views where as each view
responsible for interacting and display output to the user.
--- By convention, Views folder contains one folder for every Controller.
Eg: Views/Home for HomeController
Views/Employee for EmployeeController
For Index() action in HomeController the path will be /Views/Home/Index
So the Action method name is followed by Controller name when View()
method is returned from within the Action method like Index().
public ActionResult Index()
{
Return View();
}
In order to render a different view, specify the name of the different view
as a parameter of the View() mwthod.
public ActionResult Index()
{
Return View(“NewView”);
}

http://localhost:59265/Employee/Index
(it will open the NewView view)
Example 2:
public ActionResult display()
{
return View("ShowData");
}
------------------------------------------
Note : To access the View
http://localhost:59265/Employee/display
(it will open the ShowData view)
In order to render a different view from a different folder, specify the full
path of the different view as a parameter of the View() method.
Add the below code in HomeController (Another action method)
Create a folder Prod in Views folder in your application
Right click Views folder and add View and give the name ProdTest
Type the following code
p> this is product test view</p> in the ProdTest

public ActionResult OpenIndex()


{
return View("~/Views/Prod/ProdTest.cshtml");
}

http://localhost:1078/home/Openindex
output: ProdTest

this is product test view

How do these Views and Controllers are associated?


public class EmployeeController : Controller
{
public ActionResut Accept()
{
return View();
}
}
Demo 01:
File -> new project-> Choose Template Web-> Choose
ASP.NET MVC4 Application -> Choose Internet application->Click OK
Note : Analyse the solution explorer, run the program and close it.
Demo 02:
File -> new project-> Choose Template Web-> Choose
ASP.NET MVC4 Application -> Choose Basic application->Click OK

Go to Solution explorer-> Right click the controller folder->


add a new controller -> eg: ProductController and choose empty MVC
Template.
public class ProductController : Controller
{
//
// GET: /Product/
public ActionResult Display()
{
return View();
}
}
The above method do not have any view associated.
So , Select the display using mouse, right click -> add view--> Give view
name and click OK.
Display.cshtml:
---------------------
<h2>Welcome to ASP.NET MVC</h2>
Goto solution explorer-> Expand App_Start ->double click on
RouteConfig.cs and change the controller name and method names.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Product", action = "Display", id =
UrlParameter.Optional }

Demo 03:
-------------
File -> new project-> Choose Template Web-> Choose
ASP.NET MVC4 Application -> Choose Basic application->Click OK
Add a new controller -> EmployeeController
public class EmployeeController : Controller
{
//
// GET: /Employee/
public ActionResult Index()
{
return View();
}
}
Select the index method-> right click and add a view.
By default in solution explorer-> inside View Foler-> Employee Folder
would have got created and then index.cshtml
file would have got stored.
By default, in the routeconfig file, the name of the controller is
Home. Change that to Employee as given below.
defaults: new { controller = "Employee", action = "Index", id =
UrlParameter.Optional }
Now, add one more method to the controller.
public class EmployeeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult accept()
{
return View();
}
}
Same as click on accept-> add a view.Its gets stored in the employee
Folder.
Run the demo by default, index page appears.To view the accept page,
Modify the URL as
http://localhost:59265/Employee/accept
-----------------------------------------

Passing data/parameters from a controller to a view:


-- two ways:
1. using ViewData
2. using ViewBag
ViewData
ViewData is a dictionary object that you put data into, which then
becomes available to the view. ViewData is a derivative of the
ViewDataDictionary class, so you can access by the familiar "key/value"
syntax.
ViewBag
The ViewBag object is a wrapper around the ViewData object that
allows you to create dynamic properties for the ViewBag.
-----------------------------------------------------------------
View Data:
- we can specify the data inside the controller methods.
public ActionResult Index()
{
ViewData["k1"] = "Welcome to ASP.NET";
ViewData["k2"] = "MVC DOTNET Chapter 2";
return View();
}
-- The above data can be accessed in the view page
[index.cshtml] using the following code:

<p>@ViewData["k1"]</p>
<p>@ViewData["k2"]</p>

Example for a view bag:


public ActionResult Index()
{
ViewData["k1"] = "Welcome to ASP.NET";
ViewData["k2"] = "MVC DOTNET Chapter 2";
ViewBag.EmpID = 1001;
ViewBag.EmpName = "Rakesh";
ViewBag.Department = "Testing";
return View();
}

To access, index.cshtml
<h1>@ViewBag.EmpID</h1>
<h1>@ViewBag.EmpName</h1>
<h1>@ViewBag.Department</h1>
Difference between viewdata and viewbag is that
viewdata can handle only one data at a time,whereas viewbag has the
ability to store more than one data
--- View follows an engine called RAZOR
--- Razor is a markup language [ Combination of HTML markup code +
C# code]
-- Extension will be .cshtml or .vbhtml
The Razor syntax is based on the C# programming language, and that's
the language that's used most often with ASP.NET Web Pages.
In Razor you can create blocks of code nearly anywhere using @{ }.
Rules:
1.@Character to be used while using Serverside[C# or VB]
2. Statements should end with Semicolon
3. Variables to be declared using var keyword
4. Strings to be used with double quotes
5. C# code are case - sensitive.
The Razor code is written Views that is inside a cshtml or vbhtml.
Eg:

Single Line Codes


@{ var total = 10;}

@{ var mymessage = "Hello, World!";}

The variables can be combined with html elements.


<p> Welcome @mymessage </p>
@message

MultiLine Codes/Combining Code and Markup


@{
var mymessage = "Hello, World!";

var wday= DateTime.Now.DayOfWeek;

@for (var i = 0; i < 10; i++)


{
<div>
@message
</div>
}
@for (int i = 0; i <= 10;i++ )
{
<p>@i</P>
}

Comments

Comments in Razor can start with @* and end with *@. Nothing inside a
comment will execute or appear in the output, not even HTML markup.
@* my comments *@

Using Partial View:


-- Partial view is a common view which can reused or used by all other
views.
- These views are not associated with a particular method.

Go to solution explorer->Right click the project name-> add a new folder


-> Images-> paste some image.
Expand Views Folder-> Right click Shared Folder-> add a view-> give
name as _MyView

Note : partial views are prefixed with "_" keyword.

Add the code as given below:


_MyView.cshtml

<img width="300" height="200" src="~/Images/Tulips.jpg" />

Now , the above view can be used in any of the view pages
using the following code:

@Html.Partial("_MyView");
Routing Requests to Controller Actions

The mechanism to locate an appropriate action method for a given URL


is called Routing. In ASP MVC routing has 2 purposes.
It maps the URLs of the incoming requests with controller actions.
It builds outgoing URLs that correspond to controller actions.
Benefits of this SEO – Search Engine Optimization
ASP NET MVC defines Default route for mapping through specific
controller actions in RouteConfig.cs
When a user starts an MVC application, Application_Start() method in
the Global.asax is invoked.
This invokes RegisterRoutes() static method in RouteConfig.cs in
App_Start folder.

we have defined the Route Pattern {controller}/{action}/{id} and also


provide the default values for controller,action and id parameters. Default
values means if you will not provide the values for controller or action or
id defined in the pattern then these values will be serve by the routing
system.

Suppose your web application is running on www.example.com then the


url pattren for you application will be
www.example.com/{controller}/{action}/{id}.
Ignoring a Route
Routes.IgnoreRoute(“(resource).axd/{“pathInfo}”);

Ignores any request for files with .axd extension.

You might also like