App - Data: MVC Folder Structure
App - Data: MVC Folder Structure
App - Data: MVC Folder Structure
App_Data
The App_Data folder can contain application data files like LocalDB,
.mdf files, XML files, and other data related files. IIS will never serve
files from App_Data folder.
App_Start
The App_Start folder can contain class files that will be executed
when the application starts. Typically, these would be config files
like AuthConfig.cs, BundleConfig.cs, FilterConfig.cs, RouteConfig.cs
etc. MVC 5 includes BundleConfig.cs, FilterConfig.cs and
RouteConfig.cs by default. We will see the significance of these files
later.
App_Start Folder
Content
The Content folder contains static files like CSS files, images, and
icons files. MVC 5 application includes bootstrap.css,
bootstrap.min.css, and Site.css by default.
Content Folder
Controllers
The Controllers folder contains class files for the controllers.
A Controller handles users' request and returns a response. MVC
requires the name of all controller files to end with "Controller". You
will learn about the controller in the next section.
Controller Folder
fonts
The Fonts folder contains custom font files for your application.
Fonts folder
Models
The Models folder contains model class files. Typically model class
includes public properties, which will be used by the application to
hold and manipulate application data.
Scripts
The Scripts folder contains JavaScript or VBScript files for the
application. MVC 5 includes javascript files for bootstrap, jquery
1.10, and modernizer by default.
Scripts Folder
Views
The Views folder contains HTML files for the application. Typically
view file is a .cshtml file where you write HTML and C# or VB.NET
code.
The Views folder includes a separate folder for each controller. For
example, all the .cshtml files, which will be rendered by
HomeController will be in View > Home folder.
The Shared folder under the View folder contains all the views
shared among different controllers e.g., layout files.
View Folder
Global.asax
Global.asax file allows you to write code that runs in response to
application-level events, such as Application_BeginRequest,
application_start, application_error, session_start, session_end,
etc.
Packages.config
Packages.config file is managed by NuGet to track what packages
and versions you have installed in the application.
Web.config
Web.config file contains application-level configurations.
Routing in MVC
In the ASP.NET Web Forms application, every URL must match with
a specific .aspx file. For example, a URL
http://domain/studentsinfo.aspx must match with the file
studentsinfo.aspx that contains code and markup for rendering a
response to the browser.
Routing is not specific to the MVC framework. It can be used with ASP.NET
Webform application or MVC application.
Routing in
MVC
Configure a Route
Every MVC application must configure (register) at least one route
configured by the MVC framework by default. You can register a
route in RouteConfig class, which is
in RouteConfig.cs under App_Start folder. The following figure
illustrates how to configure a route in the RouteConfig class .
Configure Routes in MVC
As you can see in the above figure, the route is configured using
the MapRoute() extension method of RouteCollection, where name
is "Default", url pattern is "{controller}/{action}/{id}" and
defaults parameter for controller, action method and id parameter.
Defaults specify which controller, action method, or value of id
parameter should be used if they do not exist in the incoming
request URL.
URL Pattern
The URL pattern is considered only after the domain name part in
the URL. For example, the URL
pattern "{controller}/{action}/{id}" would look like
localhost:1234/{controller}/{action}/{id}. Anything after
"localhost:1234/" would be considered as a controller name. The
same way, anything after the controller name would be considered
as action name and then the value of id parameter.
Routing in MVC
If the URL doesn't contain anything after the domain name, then
the default controller and action method will handle the request. For
example, http://localhost:1234 would be handled by
the HomeController and the Index() method as configured in the
default parameter.
Multiple Routes
You can also configure a custom route using the MapRoute extension
method. You need to provide at least two parameters in MapRoute,
route name, and URL pattern. The Defaults parameter is optional.
Copy
routes.MapRoute(
name: "Student",
url: "students/{id}",
defaults: new { controller = "Student", action = "Index"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id
= UrlParameter.Optional }
);
}
}
As shown in the above code, the URL pattern for the Student route
is students/{id}, which specifies that any URL that starts
with domainName/students, must be handled by
the StudentController. Notice that we haven't specified {action} in
the URL pattern because we want every URL that starts with
students should always use the Index() action of
the StudentController class. We have specified the default
controller and action to handle any URL request, which starts
from domainname/students.
Copy
routes.MapRoute(
name: "Student",
url: "student/{id}/{name}/{standardId}",
defaults: new { controller = "Student", action = "Index", id
= UrlParameter.Optional, name = UrlParameter.Optional, standardId =
UrlParameter.Optional },
constraints: new { id = @"\d+" }
);
Register Routes
Now, after configuring all the routes in the RouteConfig class, you
need to register it in the Application_Start() event in
the Global.asax so that it includes all your routes into
the RouteTable.
Copy
Points to Remember :
1. Routing plays important role in the MVC framework. Routing maps URL to
physical file or class (controller class in MVC).
2. Route contains URL pattern and handler information. URL pattern starts after the
domain name.
3. Routes can be configured in RouteConfig class. Multiple custom routes can also
be configured.
4. Route constraints apply restrictions on the value of parameters.
5. Route must be registered in Application_Start event in Global.ascx.cs file.
Controller
In this section, you will learn about the Controller in ASP.NET MVC.
In ASP.NET MVC, every controller class name must end with a word
"Controller". For example, the home page controller name must
be HomeController, and for the student page, it must be
the StudentController. Also, every controller class must be located
in the Controller folder of the MVC folder structure.
MVC will throw "The resource cannot be found" error when you do not
append "Controller" to the controller class name.
Note:
Adding Controller
Example: Controller
Copy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
return View();
}
}
}
Now, we will return a dummy string from the Index action method
of above the StudentController. Changing the return type of Index
method from ActionResult to string and returning dummy string is
shown below. You will learn about the ActionResult in the next
section.
Example: Controller
Copy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
// GET: Student
public string Index()
{
return "This is Index action method of
StudentController";
}
}
}
Controller
Points to Remember :
1. The Controller handles incoming URL requests. MVC routing sends requests to
the appropriate controller and action method based on URL and configured
Routes.
2. All the public methods in the Controller class are called Action methods.
3. The Controller class must be derived from System.Web.Mvc.Controller class.
4. The Controller class name must end with "Controller".
5. A new controller can be created using different scaffolding templates. You can
create a custom scaffolding template also.
Action method
In this section, you will learn about the action method of the
controller class.
Action Method
As you can see in the above figure, the Index() method is public,
and it returns the ActionResult using the View() method.
The View() method is defined in the Controller base class, which
returns the appropriate ActionResult.
Default Route
Copy
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{name}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
However, you can change the default action name as per your
requirement in the RouteConfig class.
ActionResult
MVC framework includes various Result classes, which can be
returned from an action method. The result classes represent
different types of responses, such as HTML, file, string, JSON,
javascript, etc. The following table lists all the result classes
available in ASP.NET MVC.
The ActionResult class is a base class of all the above result classes,
so it can be the return type of action method that returns any result
listed above. However, you can specify the appropriate result class
as a return type of action method.
The Index() method of the StudentController in the above figure
uses the View() method to return a ViewResult (which is derived
from the ActionResult class). The base Controller class includes
the View() method along with other methods that return a particular
type of result, as shown in the below table.
As you can see in the above table, the View() method returns
the ViewResult, the Content() method returns a string,
the File() method returns the content of a file, and so on. Use
different methods mentioned in the above table to return a different
type of result from an action method.
Copy
[HttpPost]
public ActionResult Edit(Student std)
{
// update student to the database
return RedirectToAction("Index");
}
[HttpDelete]
public ActionResult Delete(int id)
{
// delete student from the database whose id matches with
specified id
return RedirectToAction("Index");
}
Points to Remember :
1. All the public methods in the Controller class are called Action methods.
2. The Action method has 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.
3. ActionResult is a base class of all the result type which returns from Action
method.
4. The base Controller class contains methods that returns appropriate result type
e.g. View(), Content(), File(), JavaScript() etc.
5. The Action method can include Nullable type parameters.
Action Selectors
Action selector is the attribute that can be applied to the action
methods. It helps the routing engine to select the correct action
method to handle a particular request. MVC 5 includes the following
action selector attributes:
1. ActionName
2. NonAction
3. ActionVerbs
ActionName
The ActionName attribute allows us to specify a different action name
than the method name, as shown below.
Copy
[ActionName("Find")]
public ActionResult GetById(int id)
{
// get student from the database
return View();
}
}
NonAction
Use the NonAction attribute when you want public method in a
controller but do not want to treat it as an action method.
Example: NonAction
Copy
[NonAction]
public Student GetStudent(int id)
{
return studentList.Where(s => s.StudentId ==
id).FirstOrDefault();
}
}
GET To retrieve the information from the server. Parameters will be appended in the query string.
HEAD Identical to GET except that server do not return the message body.
OPTIONS It represents a request for information about the communication options supported by the web server.
Copy
[HttpPost]
public ActionResult PostAction() // handles POST requests by
default
{
return View("Index");
}
[HttpPut]
public ActionResult PutAction() // handles PUT requests by default
{
return View("Index");
}
[HttpDelete]
public ActionResult DeleteAction() // handles DELETE requests by
default
{
return View("Index");
}
[HttpHead]
public ActionResult HeadAction() // handles HEAD requests by
default
{
return View("Index");
}
[HttpOptions]
public ActionResult OptionsAction() // handles OPTION requests by
default
{
return View("Index");
}
[HttpPatch]
public ActionResult PatchAction() // handles PATCH requests by
default
{
return View("Index");
}
}
Example: AcceptVerbs
Copy
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
public ActionResult GetAndPostAction()
{
return RedirectToAction("Index");}
This will add a new Student class in model folder. We want this
model class to store id, name, and age of the students. So, we will
have to add public properties for Id, Name, and Age, as shown below.
Copy
The model class can be used in the view to populate the data, as
well as sending data to the controller.
A controller can have one or more action methods, and each action
method can return a different view. In short, a controller can render
one or more views. So, for easy maintenance, the MVC framework
requires a separate sub-folder for each controller with the same
name as a controller, under the Views folder.
For example, all the views rendered from the HomeController will
resides in the Views > Home folder. In the same way, views
for StudentController will resides in Views > Student folder, as
shown below.
Note:
The Shared folder contains views, layout views, and partial views, which will be
shared among multiple controllers.
Razor View Engine
Microsoft introduced the razor view engine to compile a view with a
mix of HTML tags and server-side code. The special syntax for razor
view maximizes the speed of writing code by minimizing the number
of characters and keystrokes required when writing a view.
.vbhtml Visual Basic Razor view. Supports Visual Basic code with html tags.
The following code snippet shows the StudentController, the Student model,
and the Index.cshtml view created in the previous sections.
Example: StudentController
Copy
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
return View();
}
}
Example: Student Model class
Copy
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
Example: Index.cshtml View
Copy
@model IEnumerable<MVC_BasicTutorials.Models.Student>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
Now, to run it successfully, we need to pass a model object from an action method to
a view. As you can see in the above Index.cshtml, it
uses IEnumerable<Student> as a model type. So we need to pass it from
the Index() action method of the StudentController class, as shown below.
return View(studentList);
}
}
Try it
As you can see in the above code, we have created a list of student objects for an
example purpose (in real-life application, you can fetch it from the database). We
then pass this list object as a parameter in the View() method. The View() method is
defined in the base Controller class, which automatically binds a model object to a
view.
Now, you can run the MVC project by pressing F5 and navigate
to http://localhost/Student. You will see the following view in the browser.
Bind Query String to an Action Method
Parameters in MVC
Here, you will learn about to bind a model object to an action
method parameters in the ASP.NET MVC application.
The model binding refers to converting the HTTP request data (from
the query string or form collection) to an action method parameters.
These parameters can be of primitive type or complex type.
Model
Binding
You can also have multiple parameters in the action method with
different data types. Query string values will be converted into
parameters based on the matching names.
Copy
return View();
}
Now, you can create an action method which includes the Student
type parameter. In the following example, Edit action method
(HttpPost) includes Student type parameter.
Copy
[HttpPost]
public ActionResult Edit(Student std)
{
var id = std.StudentId;
var name = std.StudentName;
var age = std.Age;
var standardName = std.standard.StandardName;
return RedirectToAction("Index");
}
FormCollection
You can also include the FormCollection type parameter in the
action method instead of a complex type to retrieve all the values
from view form fields, as shown below.
Bind Attribute
ASP.NET MVC framework also enables you to specify which
properties of a model class you want to bind. The [Bind] attribute
will let you specify the exact properties of a model should include or
exclude in binding.
Copy
[HttpPost]
public ActionResult Edit([Bind(Include = "StudentId, StudentName")]
Student std)
{
var name = std.StudentName;
return RedirectToAction("Index");
}
Copy
[HttpPost]
public ActionResult Edit([Bind(Exclude = "Age")] Student std)
{
var name = std.StudentName;
return RedirectToAction("Index");
}