App - Data: MVC Folder Structure

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

ASP.

NET MVC Folder Structure


Here, you will learn about the ASP.NET MVC project structure. Visual
Studio creates the following folder structure of the ASP.NET MVC
application by default.

MVC Folder Structure

Let's see significance of each folder.

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

Additionally, MVC project also includes the following configuration


files:

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.

Learn how the ASP.NET MVC framework handles requests using


routing in the next section.

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.

ASP.NET introduced Routing to eliminate the needs of mapping each


URL with a physical file. Routing enables us to define a URL pattern
that maps to the request handler. This request handler can be a file
or class. In ASP.NET Webform application, request handler is .aspx
file, and in MVC, it is the Controller class and Action method. For
example, http://domain/students can be mapped to
http://domain/studentsinfo.aspx in ASP.NET Webforms, and the
same URL can be mapped to Student Controller and Index action
method in MVC.
Route
Route defines the URL pattern and handler information. All the
configured routes of an application stored in RouteTable and will be
used by the Routing engine to determine appropriate handler class
or file for an incoming request.

The following figure illustrates the Routing process.

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.

In the same way, you can configure other routes using


the MapRoute() method of the RouteCollection class.
This RouteCollection is actually a property of the RouteTable class.

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.

The following table shows which Controller, Action method, and Id


parameter would handle different URLs considering the above
default route.

URL Controller Action Id

http://localhost/home HomeController Index null

http://localhost/home/index/123 HomeController Index 123

http://localhost/home/about HomeController About null

http://localhost/home/contact HomeController Contact null

http://localhost/student StudentController Index null

http://localhost/student/edit/123 StudentController Edit 123

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.

You can register multiple custom routes with different names.


Consider the following example where we register "Student" route.

Example: Custom Routes

Copy

public class RouteConfig


{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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.

MVC framework evaluates each route in sequence. It starts with the


first configured route, and if incoming URL doesn't satisfy the URL
pattern of the route, then it will evaluate the second route and so
on. In the above example, routing engine will evaluate
the Student route first and if incoming URL doesn't start
with /students then only it will consider the second route which is
the default route.

The following table shows how different URLs will be mapped to


the Student route:

URL Controller Action Id

http://localhost/student/123 StudentController Index 123

http://localhost/student/index/123 StudentController Index 123

http://localhost/student?Id=123 StudentController Index 123


Route Constraints
You can also apply restrictions on the value of the parameter by
configuring route constraints. For example, the following route
applies a limitation on the id parameter that the id's value must be
numeric.

Example: Route Constraints

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+" }
);

So if you give non-numeric value for id parameter, then that request


will be handled by another route or, if there are no matching routes,
then "The resource could not be found" error will be thrown.

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.

Example: Route Registration

Copy

public class MvcApplication : System.Web.HttpApplication


{
protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}

The following figure illustrate Route registration process.


Register Route

Thus, routing plays important role in MVC framework.

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.

The Controller in MVC architecture handles any incoming URL


request. The Controller is a class, derived from the base
class System.Web.Mvc.Controller. Controller class contains public
methods called Action methods. Controller and its action method
handles incoming browser requests, retrieves necessary model data
and returns appropriate responses.

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.

Adding a New Controller


Now, let's add a new empty controller in our MVC application in
Visual Studio.

MVC will throw "The resource cannot be found" error when you do not
append "Controller" to the controller class name.

In the previous section, we learned how to create our first MVC


application, which created a default HomeController. Here, we will
create new StudentController class.

In the Visual Studio, right click on the Controller folder ->


select Add -> click on Controller..
Add New Controller

This opens Add Scaffold dialog, as shown below.

Note:

Scaffolding is an automatic code generation framework for ASP.NET web


applications. Scaffolding reduces the time taken to develop a controller, view, etc.
in the MVC framework. You can develop a customized scaffolding template using
T4 templates as per your architecture and coding standards.
Adding Controller

Add Scaffold dialog contains different templates to create a


new controller. We will learn about other templates later. For now,
select "MVC 5 Controller - Empty" and click Add. It will open the Add
Controller dialog, as shown below

Adding Controller

In the Add Controller dialog, enter the name of the controller.


Remember, the controller name must end with Controller.
Write StudentController and click Add.
Adding Controller

This will create the StudentController class with


the Index() method in StudentController.cs file under the
Controllers folder, as shown below.

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();
}
}
}

As you can see above, the StudentController class is derived from


the Controller class. Every controller in MVC must be derived from
this abstract Controller class. This base Controller class contains
helper methods that can be used for various purposes.

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";
}
}
}

We have already seen in the routing section that the URL


request http://localhost/student or http://localhost/student/in
dex is handled by the Index() method of
the StudentController class, as shown above. So let's invoke it from
the browser and you will see the following page in the browser.

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.

All the public methods of the Controller class are


called Action methods. They are like any other normal methods with
the following restrictions:

1. Action method must be public. It cannot be private or protected


2. Action method cannot be overloaded
3. Action method cannot be a static method.

The following illustrates the Index() action method in


the StudentController 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 Action Method


Every controller can have a default action method as per the
configured route in the RouteConfig class. By default,
the Index() method is a default action method for any controller, as
per configured default root, as shown below.

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.

Result Class Description

ViewResult Represents HTML and markup.

EmptyResult Represents No response.

ContentResult Represents string literal.

FileContentResult/ FilePathResult/ FileStreamResult Represents the content of a file.

JavaScriptResult Represent a JavaScript script.

JsonResult Represent JSON that can be used in AJAX.

RedirectResult Represents a redirection to a new URL.

RedirectToRouteResult Represent another action of same or other controller.

PartialViewResult Returns HTML from Partial view.

HttpUnauthorizedResult Returns HTTP 403 status.

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.

Result Class Description Base Controller Method

ViewResult Represents HTML and markup. View()

EmptyResult Represents No response.

ContentResult Represents string literal. Content()

FileContentResult, Represents the content of a file. File()


FilePathResult,
FileStreamResult

JavaScriptResult Represents a JavaScript script. JavaScript()

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

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

RedirectToRouteResult Represents redirection to another route. RedirectToRoute()

PartialViewResult Represents the partial view result. PartialView()

HttpUnauthorizedResult Represents HTTP 403 response.

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.

Action Method Parameters


Every action methods can have input parameters as normal
methods. It can be primitive data type or complex type parameters,
as shown below.

Example: Action Method Parameters

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");
}

Please note that action method paramter can be Nullable Type.

By default, the values for action method parameters are retrieved


from the request's data collection. The data collection includes
name/values pairs for form data or query string values or cookie
values. Model binding in ASP.NET MVC automatically maps the URL
query string or form data collection to the action method parameters
if both names match. Visit model binding section for more
information on it.

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.

Example: Specify a different action name

Copy

public class StudentController : Controller


{
public StudentController()
{
}

[ActionName("Find")]
public ActionResult GetById(int id)
{
// get student from the database
return View();
}
}

In the above example, we have applied ActioName("find") attribute


to the GetById() action method. So now, the action method name
is Find instead of the GetById. So now, it will be invoked
on http://localhost/student/find/1 request instead
of http://localhost/student/getbyid/1 request.

NonAction
Use the NonAction attribute when you want public method in a
controller but do not want to treat it as an action method.

In the following example, the Index() method is an action method,


but the GetStudent() is not an action method.

Example: NonAction
Copy

public class StudentController : Controller


{
public string Index()
{
return "This is Index action method of StudentController";
}

[NonAction]
public Student GetStudent(int id)
{
return studentList.Where(s => s.StudentId ==
id).FirstOrDefault();
}
}

ActionVerbs: HttpGet, HttpPost, HttpPut


The ActionVerbs selector is to handle different type of Http requests.
The MVC framework includes HttpGet, HttpPost, HttpPut,
HttpDelete, HttpOptions, and HttpPatch action verbs. You can 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.

The following table lists the usage of HTTP methods:

Http method Usage

GET To retrieve the information from the server. Parameters will be appended in the query string.

POST To create a new resource.

PUT To update an existing resource.

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.

DELETE To delete an existing resource.

PATCH To full or partial update the resource.


Visit W3.org for more information on Http Methods.

The following example shows how to handle different types of HTTP


requests in the Controller using ActionVerbs:

Example: Handle HTTP Requests in the Controller

Copy

public class StudentController : Controller


{
public ActionResult Index() // handles GET requests by default
{
return View();
}

[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");
}
}

You can also apply multiple action verbs using


the AcceptVerbs attribute, as shown below.

Example: AcceptVerbs

Copy

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
public ActionResult GetAndPostAction()
{
return RedirectToAction("Index");}

Model in ASP.NET MVC


In this section, you will learn about the model class in ASP.NET MVC
framework.

The model classes represents domain-specific data and business


logic in the MVC application. It represents the shape of the data as
public properties and business logic as methods.

In the ASP.NET MVC Application, all the Model classes must be


created in the Model folder.

Adding a Model Class


Let's create the model class that should have the required properties
for the Student entity.

In the MVC application in Visual Studio, and right-click on


the Model folder, select Add -> and click on Class... It will open
the Add New Item dialog box.
In the Add New Item dialog box, enter the class name Student and
click Add.

Create Model Class

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.

Example: Model class

Copy

public class Student


{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}

The model class can be used in the view to populate the data, as
well as sending data to the controller.

Create a View in ASP.NET MVC


In this section, you will learn how to create a view and use the model
class in it in the ASP.NET MVC application.

A view is used to display data using the model class object.


The Views folder contains all the view files in the ASP.NET MVC
application.

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.

View folders for Controllers

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.

The razor view uses @ character to include the server-side code


instead of the traditional <% %> of ASP. You can use C# or Visual
Basic syntax to write server-side code inside the razor view.

ASP.NET MVC supports the following types of razor view files:

File extension Description

.cshtml C# Razor view. Supports C# code with html tags.

.vbhtml Visual Basic Razor view. Supports Visual Basic code with html tags.

.aspx ASP.Net web form

.ascx ASP.NET web control

Integrate Controller, View and Model


We have already created a Controller, a model and a view in the previous sections.
Here, we will integrate them to run the application and see the result.

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>

@foreach (var item in Model) {


<tr>
<td>
@Html.DisplayFor(modelItem => item.StudentName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.StudentId
}) |
@Html.ActionLink("Details", "Details", new {
id=item.StudentId }) |
@Html.ActionLink("Delete", "Delete", new { id =
item.StudentId })
</td>
</tr>
}
</table>

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.

Example: Passing Model from Controller


Copy
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
var studentList = new List<Student>{
new Student() { StudentId = 1,
StudentName = "John", Age = 18 } ,
new Student() { StudentId = 2,
StudentName = "Steve", Age = 21 } ,
new Student() { StudentId = 3,
StudentName = "Bill", Age = 25 } ,
new Student() { StudentId = 4,
StudentName = "Ram" , Age = 20 } ,
new Student() { StudentId = 5,
StudentName = "Ron" , Age = 31 } ,
new Student() { StudentId = 4,
StudentName = "Chris" , Age = 17 } ,
new Student() { StudentId = 4,
StudentName = "Rob" , Age = 19 }
};
// Get the students from the database in the real
application

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.

Binding to Primitive Type


The HTTP GET request embeds data into a query string. MVC
framework automatically converts a query string to the action
method parameters provided their names are matching. For
example, the query string id in the following GET request would
automatically be mapped to the Edit() action
method's id parameter.

Model
Binding

This binding is case insensitive. So "id" parameter can be "ID" or "Id".

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.

For example, the query string parameters of an HTTP


request http://localhost/Student/Edit?id=1&name=John would
map to id and name parameters of the following Edit() action
method.

Example: Convert QueryString to Action Method Parameters

Copy

public ActionResult Edit(int id, string name)


{
// do something here

return View();
}

Binding to Complex Type


Model binding also works on complex types. It will automatically
convert the input fields data on the view to the properties of a
complex type parameter of an action method in HttpPost request if
the properties' names match with the fields on the view.

Example: Model classes in C#


Copy

public class Student


{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
public Standard standard { get; set; }
}

public class Standard


{
public int StandardId { get; set; }
public string StandardName { get; set; }
}

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.

Example: Action Method with Class 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;

//update database here..

return RedirectToAction("Index");
}

Thus, the MVC framework will automatically map Form collection


values to the Student type parameter when the form submits an
HTTP POST request to the Edit() action method, as shown below.
Model Binding to Complex Type

So thus, it automatically binds form fields to the complex type


parameter of action method.

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.

Model Binding to FormCollection

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.

In the following example, the Edit() action method will only


bind StudentId and StudentName properties of the Student model
class.

Example: Binding Parameters

Copy
[HttpPost]
public ActionResult Edit([Bind(Include = "StudentId, StudentName")]
Student std)
{
var name = std.StudentName;

//write code to update student

return RedirectToAction("Index");
}

You can also exclude the properties, as shown below.

Example: Exclude Properties in Binding

Copy

[HttpPost]
public ActionResult Edit([Bind(Exclude = "Age")] Student std)
{
var name = std.StudentName;

//write code to update student

return RedirectToAction("Index");
}

The Bind attribute will improve the performance by only bind


properties that you needed.

Model Binding Process


As you have seen, that the ASP.NET MVC framework automatically
converts request values into a primitive or complex type object.
Model binding is a two-step process. First, it collects values from the
incoming HTTP request, and second, it populates primitive type or
a complex type with these values.

Value providers are responsible for collecting values from requests,


and Model Binders are responsible for populating values.
Model
Binding in ASP.NET MVC

Default value provider collection evaluates values from the following


sources:

1. Previously bound action parameters, when the action is a child action


2. Form fields (Request.Form)
3. The property values in the JSON Request body (Request.InputStream), but
only when the request is an AJAX request
4. Route data (RouteData.Values)
5. Querystring parameters (Request.QueryString)
6. Posted files (Request.Files)

MVC includes DefaultModelBinder class which effectively binds most


of the model types.

You might also like