mvc
TRANSCRIPT
MVC or Model View Controller is a design pattern. This design pattern has been present in software applications for several decades. The Model View Controller pattern was invented in a Smalltalk context for decoupling the graphical interface of an application from the code that actually does the work.
* Model-Consist of Application data and the business rules. It contains the code to manipulate the data (From Database or any data source) & Also the Objects that retrieve the data. It represent the state of particular aspect of the application. Eg: Model Maps to Database Table and entries in table represent the state of the application. Model is responsible for actual data processing, like database connection, querying database, implementing business rules etc. It feeds data to the view without worrying about the actual formatting and look and feel.
* Controller- Handles user interaction, Reads data from view, Controls Input & Send input data to the model. Handles Inputs and update the model to reflect the change in state of the application. It also pass information to the view. Controller is responsible for Notice of action. Controller responds to the mouse or keyboard input to command model and view to change. Controllers are associated with views. User interaction triggers the events to change the model, which in turn calls some methods of model to update its state to notify other registered views to refresh their display.
* View-Is an output, It could be a webpage or a printout. In short views are used to display the data. Most of the time we create views from the model data. It accepts information from the controller and displays it. View is the graphical data presentation (outputting) irrespective of the real data processing. View is the responsible for look and feel, some custom formatting, sorting etc. View is completely isolated from actual complex data operations.
1. Separation of Concerns
2. Better Support for Test Driven Development
3. Clean URL
4. Better for Search Engine Optimization
5. Full Control over the User Interface or the HTML
6. Loosely coupled so Each Component can be tested independently.
Controllers and Action Methods in ASP.NET MVC Applications
Before entering to the coding side we must have some basic knowledge about MVC that is what MVC is,, what are its applications and what are the advantages of using MVC architecture etc..
ASP.NET MVC is the Microsoft's Web application frame work and the other one is the web form frame work.
As the name specifies MVC contains
1. Model
2.View
3.Controller
MVC Frameworks maps the URLs to Controllers (or controller action methods.). And the controller processes the input or incoming request and calls a View (That is our html output).Model does the business logics in the projects that needed by the View to populates the output and controller used the model to save data, update data etc.
Controller class is responsible for
1. Locating the action methods.
2. Getting the arguments for action method.
3. Processing the action method and handles the errors during the processing phase.
4. Call the appropriate View (Html output) pages
Action Methods
User gives request to the controller via URL. And the Controller processes the requests using the
action methods defined by the Controller. For example the given below is the HomeController for a
new project. Index and About are the action method of HomeController.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication2.Controllers
{
public class HomeController : Controller
{ public ActionResult Index()
{ ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(); }
public ActionResult About()
{ return View(); } }}
To invoke the Index method of the HomeController, the URL is
http: xxxxx/Home or http: xxxxx/Home/Index
Because of Index is the default method there is no need to Specify /Home/Index.
And to invoke About method
http://localhost:3471/Home/About
ActionResult Return Type
There are different types of results that are available to you in ASP.NET MVC 3. When creating new
controllers, they will come with one or more actions by default.The Empty controller includes an
Index action with a return value of type ActionResult. ActionResult class is the base class for all
action results.There are different ActionResult types are there,briefly explained below.
ActionResult Helper Method Description
ViewResult View Renders a view as a web page
PartialViewResult PartialViewSection of a view,that can be rendered inside
another view
RedirectResult Redirect Redirect to another action method
RedirectToRouteResult RedirectToRoute Redirect to another action method
ContentResult Content Returns a user-defined content type
JsonResult Json Retuns a serialized JSON object
JavaScriptResult JavaScript Returns a script that can be executed on the client
FileResult File Returns a binary output to write to the response
EmptyResult (None) returns a null result
Action Methods Parameters
Request and Reaponse methods can be called from the action method of the controller.If the
parameter to an action method is passing through the URL, there are several ways to access it into
our action method.
The below code explains how to use Request object to access the query-string value.
public void Register()
{ int ID = Convert.ToInt32(Request["ID "]);}
This Tutorial is intended for people who are not familiar with assembly language or assembler at all.
This tutorial will take u though step by step instructions to start creating programs in assembly
language. Even if you are familiar with assembly language this website would be handy if you would
like to go though 8086 instructions or interrupts. We would focus mostly on the coding aspect than
theory.
Non-Action Methods All action methods in a Controller are defined as public method.If you want some method as non
action method,mark the method with NonAction Attribute
[NonAction]
private void function_name()
{ // Method logic.}
Views and UI rendering in ASP.NET MVC
The ASP.NET MVC framework supports view engine to generate views (UI).
Default view page Index.cshtml
@{ ViewBag.Title = "Home Page";}
<h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc"
title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet"
type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"
type="text/javascript"></script>
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>New Project</h1>
</div>
<div id="logindisplay">
@Html.Partial("_LogOnPartial")
</div>
<div id="menucontainer">
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
</div>
</div>
<div id="main">
@RenderBody()
</div>
<div id="footer">
</div>
</div>
</body>
</html>
Automatic Mapping of Action Method Parameters and Incoming Request
Consider our action method have some parameters,mapping of user request data to the parameter
is done automatically in MVC framework.MVC framework examines the user request that if there is
an HTTP request value with same name,then it maps the value automatically to the parameter of
action method.
Consider an examle,Suppose we have a Controller 'Register' and an action method 'Add' in
'Register' Controller.
public ActionResult Add(int id)
{ ViewData["RegisterNumber"] = id;
return View();}
We can also embed the parameter with the URL itself instead of as query-string values.
For example we the URL may be ../Register/Add/5
The default route mapping rule has the format ../{Controller}/{action}/{id}
Helper Classes
There are several Helper classes in MVC frame work.
1.Form Helper- Radio buttons, textboxes,list boxes etc.
2.URL helpers
3.HTML helpers- Encode, Decode, AttributeEncode, and RenderPartial.
Rendering Form using HTML Helpers
Some of the commonly used HTML helpers are
* ActionLink : Link to an action method
@Html.ActionLink("About MVC", "About", "Home")
When We click on th link 'About MVC' it links to the 'About' method in the 'HomeController'.
*TextBox
name: @Html.TextBox("name")
*BeginForm- Marks the start of a form and links to the action method that renders the form.
@using (Html.BeginForm("AddDetails", "admin", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
-----Form Content-----
}
When the from submits the data goes to 'AddDetails' action method in the 'adminController'.
*DropDownList- Renders a drop-down list.
The code for the 'Countries' Action method
public ActionResult Countries()
{
List countryList = new List();
countryList.Add("India");
countryList.Add("Pakistan");
countryList.Add("USA");
countryList.Add("Afghanistan");
countryList.Add("China");
countryList.Add("France");
countryList.Add("Japan");
ViewBag.countries = new SelectList(countryList);
return View(); }
The View page of 'Countries' will Contain
Countries :@Html.DropDownList("countries ")
* RadioButton
Select your Country:
@Html.RadioButton("country", "India", true)India
@Html.RadioButton("country", "Pakistan", false)Pakistan
@Html.RadioButton("country", "USA", false)USA
@Html.RadioButton("country", "Afghanistan", false)Afghanistan
@Html.RadioButton("country", "China", false)China
@Html.RadioButton("country", "France", false)France
@Html.RadioButton("country", "Japan", false)Japan
* CheckBox
@Html.CheckBox("country")
* TextArea-Multi-line text box.
URL Helper classes
URL Helper class provide the following methods.
1. Action- Generates a URL that maps to an action method.
Overload Lists.
*Action(String)
*Action(String, Object)
*Action(String, String)
*Action(String, RouteValueDictionary)
*Action(String, String, Object)
*Action(String, String, RouteValueDictionary)
*Action(String, String, Object, String)
*Action(String, String, RouteValueDictionary, String, String)
Syntax for Action(String)
public string Action( string actionName)
2.RouteUrl-Generates a URL that maps to a route.
Overload Lists.
*RouteUrl(Object)
*RouteUrl(String)
*RouteUrl(RouteValueDictionary)
*RouteUrl(String, Object)
*RouteUrl(String, RouteValueDictionary)
*RouteUrl(String, Object, String)
*RouteUrl(String, RouteValueDictionary, String, String)
Syntax for RouteUrl(Object)
public string RouteUrl( Object routeValues)
3.Content-Generates a URL path to a resource, based on the virtual (relative) path of the resource.
Syntax
public string Content( string contentPath)
4.Encode- This method encodes special characters in the specified URL into character-entity
equivalents.
Syntax
public string Encode( string url)
HTML Helper classes
MVC include HTML Helpers like links and HTML form elements.
Links include HTML.ActionLink() helper.
Razor syntax of ActionLink is
@Html.ActionLink("About MVC", "About", "Home")
The Html.ActionLink() helper above, outputs the following HTML:
<a href="/Home/About">About MVC</a>
HTML Form Elements
*Html.BeginForm() *Html.CheckBox() *Html.DropDownList() *Html.EndForm()
*Html.Hidden() *Html.ListBox() *Html.Password() *Html.RadioButton() *Html.TextArea()
*Html.TextBox()
@Html.ValidationSummary("Create was unsuccessful. Please correct the
errors and try again.")
@using (Html.BeginForm()){
<p>
<label for="FirstName">First Name:</label>
@Html.TextBox("FirstName")
@Html.ValidationMessage("FirstName", "*")
</p>
<p>
<label for="LastName">Last Name:</label>
@Html.TextBox("LastName")
@Html.ValidationMessage("LastName", "*")
</p>
<p>
<label for="gender">Gender:</label>
@Html.RadioButton("gender", "Male", true) Male
@Html.RadioButton("gender", "Female", false) Female
</p>
<p>
<label for="Password">Password:</label>
@Html.Password("Password")
@Html.ValidationMessage("Password", "*")
</p>
<p>
<label for="Password">Confirm Password:</label>
@Html.Password("ConfirmPassword")
@Html.ValidationMessage("ConfirmPassword", "*")
</p>
<p>
<label for="Profile">Profile:</label>
Action Link
Action Link helper method is used to link to an action method.
Syntax of ActionLinkHelper method
@Html.ActionLink("Show list", "Index", "Country")
it links to 'Index' method in 'CountryController'.
Output the following HTML
<a href="Country/Index">Show list</a>
Begin Form - BeginForm helper class help to POST the form content to action method.
Syntax of BeginForm Helper method
@using (Html.BeginForm("AddDetails", "Home", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{ -----Form Content-----}
Output the following HTML
<form action="Home/AddDetails" method=POST>
Radio Button Syntax of Radio Button Helper method
@Html.RadioButton("gender", "Male", true) Male
@Html.RadioButton("gender", "Female", false) Female
Output the following HTML
<input type="radio" value="Male" name="gender" />Male
<input type="radio" value="Female" name="gender" />Female
Check Box Helper
Syntax of Razor CheckBox helper
@Html.CheckBox("ReceiveNewsletter")I agree
Output the HTML
<input type="checkbox" name="ReceiveNewsletter" />I agree
ViewBag - 'ViewBag' and 'ViewData' have the same functionalities.It can store data.ViewBag is
used to pass data from controller to view
The action method contain
List color = new List();
color.Add("blue");
color.Add("green");
color.Add("red");
ViewBag.Colors= color;
ViewBag.name = "ABC";
ViewBag.age = 25;
The View contains
My name is
@ViewBag.name
Age:@ViewBag.age
Color:@Html.DropDownList("Colors")
Default Home Controller -When we start to create a new project,a default home controller with
Index(),About() action method will provided.
HomeController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication3.Controllers
{ public class HomeController : Controller
{ public ActionResult Index()
{ ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(); }
public ActionResult About()
{ return View(); } }}
Master Pages In ASP .NET MVC or Using Layout For Common Site Elemnts
Layout for Common site Elements
Layout page is used to add some common site elements.
Go to Views>>Shared>>_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet"
type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"
type="text/javascript"></script>
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>My MVC Application</h1>
</div>
<div id="logindisplay">
@Html.Partial("_LogOnPartial")
</div>
<div id="menucontainer">
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
</div>
</div>
<div id="main">
@RenderBody()
</div>
<div id="footer">
</div>
</div>
</body>
</html>
Run the default project...
Change the layout page according to our needs..Suppose we want another link,'Contact us' ... add
the following code in _Layout.cshtml..
<li>@Html.ActionLink("Contact us", "Contact", "Home")</li>
Add Home controller action method(Contact()) and View for that action method.Then run the project.
Next change the heading My MVC Application to New Project
Introduction to DbContext and DbSet
DbContext :Simplfied alternative to ObjectContext and is the primary object for interacting with a
database using a specific model.
DbSet : Simplified alternative to ObjectSet and is used to perform CRUD operations against a
specific type from the model.
DbContext and DbSet is used for the CodeFirst appraoch.Which enables a very clean and rapid
development workflow.
Suppose we want to create a database called 'NewDatabase' and two tables in that called 'State'
and 'Country'.Then write the Model classes..
Goto Models rigtht click on Models>>Add>>Class
Add a model class and name it as Country.cs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication2.Models
{
public class Country
{ [Key]
public virtual int country_id {get; set; }
[Required ]
public virtual string country_name { get; set;} }}
Similarly add another class and named it as State.cs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication2.Models
{ public class State
{ [Key]
public virtual int state_id {get; set; }
[Required ]
public virtual string state_name { get; set;} }}
Add another Model class 'NewDatabase.cs'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcApplication2.Models
{ public class NewDatabase:DbContext
{
public DbSet Country { get; set; }
public DbSet State { get; set; } }}
Goto HomeController
Goto Views>>Index.cshtml
Accessing Models Data from Controller
The below given example shows how to acces Models Data from Controller.
Create new project,add Context class 'NewDatabase.cs' and Model class 'Country.cs'
NewDatabase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcApplication2.Models
{ public class NewDatabase:DbContext
{ public DbSet<country>Country { get; set; } }}
Country.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication2.Models
{ public class Country
{ [Key]
public virtual int country_id {get; set; }
[Required ]
public virtual string country_name { get; set;} }}
Add a Controller 'CountryController'
CountryController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
namespace MvcApplication2.Controllers
{ public class CountryController : Controller
{ // // GET: /Country/
NewDatabase db = new NewDatabase();
public ActionResult Index()
{ //Shows Country details
var model = db.Country;
return View(model); }
public ActionResult AddCountry()
{ return View(); }
[HttpPost]
public ActionResult AddCountry(Country model)
{
// Attempt to add the country name
db.Country.Add(model);
db.SaveChanges();
return View(model); } }}
Run the Project
Using a Model to pass data to our View
Basically a view template is an HTML output for viewers,if we want to create dynamic web pages we
need to pass informations from controller to views.Model class represents to the tables in our
database and Model classes can be used to access database values,these Model data passes to
views to create webpages,that is done by the controller.
Let us go through the example....
Create Context class 'Newdatabase' and model class for representing Country table in our database,
'Country.cs' as explained earlier in Accessing Model Data From Controller
Add ActionMethod in CountryController...
public ActionResult countryDetails(int id)
{ Country country = db.Country.Find(id);
return View(country); }
Add a View for the action method..Right Click inside 'countryDetails' >>Add View
countryDetails.cs
@model MvcApplication2.Models.Country
@{ ViewBag.Title = "countryDetails";}
<h2>countryDetails</h2>
Country name: @Html.DisplayFor(model => model.country_name)
Run the project with Url: ../Country/countryDetails/1
Changing Views and Layout
We can change the Layout page and view page of our project.
Let us start with an example....Create a new project,named it as 'Countries'.
The default project will run like this..
We want to change the heading 'My Mvc Application' which is common to all pages to 'Country Lists'
Goto Views>>Shared>>_Layout.cshtml
Change the title to 'Country Lists'
run the project
Change the Content....
Run the project to see the changes...
to Change the message 'Welcome to ASP.NET MVC'..,Goto HomeController>>Index method
Change the ViewBag Data.
Partial Views
A partial view enables you to define a view that will be rendered inside a parent view. Partial views
are implemented as ASP.NET user controls (.ascx).
When a partial view is instantiated, it gets its own copy of the ViewDataDictionary object that is
available to the parent view. The partial view therefore has access to the data of the parent view.
However, if the partial view updates the data, those updates affect only the partial view's ViewData
object. The parent view's data is not changed. By using partial view we can render a view inside a
parental view and to create reusable content in the project.
Go through the given example .Create a Model class for partial view named it as 'PartialModel2.cs'
PartialModel2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication2.Models
{ public partial class PartialModel2
{ public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; } }
public partial class PartialModel2
{ public List<PartialModel2> partialModel { get; set; } }}
Add the following methods in HomeController.
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
namespace MvcApplication2.Controllers
{ public class HomeController : Controller
{ public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(new PartialModel2() { partialModel =
Sampledetails() });
}
private List<partialmodel2> Sampledetails()
{ List<partialmodel2> model = new List<partialmodel2>();
model.Add(new PartialModel2()
{ Name = "Rima", Age = 20, Address="Kannur" });
model.Add(new PartialModel2()
{ Name = "Rohan", Age = 23, Address = "Ernakulam" });
model.Add(new PartialModel2()
{Name = "Reshma", Age = 22, Address = "Kannur" });
return model; } }}
Add Partial View
Views>>Right click on 'Home'>>Add>>View
Name the View as'PartialView1' and Check on the checkbox 'Create as a partial view',the click on
'Add' button.
PartialView1.cshtml
@model IEnumerable<MvcApplication2.Models.PartialModel2 >
@using MvcApplication2.Models
@if (Model != null)
{ <div class="grid">
<table cellspacing="0" width="80%">
<thead> <tr> <th>Name </th> <th>Age</th>
<th>Address</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td align="left">
@item.Name
</td>
<td align="left">
@item.Age
</td>
<td align="left">
@item.Address
</td> </tr>}</tbody></table></div>}
Render the partial view into Index(parental) view.
Index.cshtml
@model MvcApplication2 .Models.PartialModel2
@{ ViewBag.Title = "Home Page";}
<p> <div>@Html.Partial("PartialView1", Model.partialModel) </div></p>
Run the project
MVC ViewDataDictionary Represents a container that is used to pass data between a controller and a view.
Accessing Data From View to Controller
The Properties of the ViewDataDictrionary are
> Count | Gets the number of elements in the collection.
> IsReadOnly
> Item
> Keys
> Model | Gets or sets the model that is associated with the view data.
> ModelMetadata
> ModelState
> TemplateInfo
> Values | Gets a collection that contains the values in this dictionary.
Request.Form[“CountryCode”]
NonActionAttribute in mvc
Partial View
MVC Helper
Passing Data Between Action Methods
MVC ActionFilter Like [Authozie]
By default mvc treats all public methods in a controller as action methods. U can mark some
of the methods as non action methods using the NonActionAttribute attribute.Eg.
[NonAction]
private void DoSomething()
{
}
> Action Methods might have to pass data to another action.
> An action method can store data in the controller's TempDataDictionary object
before it calls the controller's RedirectToAction method to invoke the next action.
The TempData property value is stored in session state. Any action method that is
called after the TempDataDictionary value is set can get values from the object and
then process or display them. The value of TempData persists until it is read or
until the session times out. Persisting TempData in this way enables scenarios
such as redirection, because the values in TempData are available beyond a single
request.
How to publish the mvc solution u have created to a website
HTML Helpers
> Html.Raw
TagBuilder
Helper MVCHtmlString
When u want to return non htmlencoded helpers
PartialView
Html.Action
[ChildActionOnly]
DefaultModelBinder
JQuery
JQuery is a javascript library .Is used to add client side features to the application.
JqueryUI
Is a jquery Plugin
This library includes a number of animation effects, Widgets Like Dialogs , Sliders,
Accordians, Tabs, Autocomplete,
UnObtrusive Javascript
Custom Action Filters
Create a Class . Eg HelloWorldAttribute
Derieve it from Action Filter Attribute
Override Methods Like ActionExecuting, ActionExecuted etc .
[HelloWorld] can be given controller wide or for an Action Method
To Make it effective application wide. Open global.asax.cx and add filters.add(new
HellowWorldAttribute() ); in the Register Global Filters
This can be used logging .
View Where Data is rendred from different action Methods
http://muruganad.com/ASP.NET/MVC/Create-Mvc-view-by-rendering-data-from-differenet-
action-methods.html
1. Build the solution.
2. Right click on the project in Solution Explorer . Select Publish option.
3. if the webserver doesnot have MVC installed, copy the folloing dlls to the bin folder of your
website before building the solution.
dlls to be copied to the bin folder:
a. System.Web.MVC.dll
b. System.Web.Routing.dll c. System.Web.Extensions.dll
The dlls can be found by checking the physical folder path of these dlls in the reference
folder.
do the steps 1 and 2 above.
Copy the files from the Publish folder to the destination folder on your website.
MVC Get Dropdown Selected Text
asp .net mvc populate a dropdownlist from DataSet
LIST OF ATTRIBUTES
1. ActionMethodSelectorAttribute
2. ActionNameAttribute
3. ActionNameSelectorAttribute : Represents an attribute that affects the
selection of an action method.
4. AllowHtmlAttribute : Allows a request to include HTML markup during
model binding by skipping request validation for the property. (It is
strongly recommended that your application explicitly check all models
where you disable request validation in order to prevent script
exploits.)
5. AllowAnonymousAttribute : Represents an attribute that marks
controllers and actions to skip the AuthorizeAttribute during
authorization.
6. AuthorizeAttribute : Represents an attribute that is used to restrict
access by callers to an action method.
7. BindAttribute : Represents an attribute that is used to provide
details about how model binding to a parameter should occur.
There is no way to directly get value from a Html.DropDownList .
The alternative is to make a hidden fieled. thats get populated by javascript
on click of a button or selectedindex change of dropdownlist.
// Controller CODE.
List list = new List { };
foreach(DataRow oDataRow in oCountry.DataSetCountry.Tables[0].Rows)
{
SelectListItem oSelectListItem = new SelectListItem { Value =
(String)oDataRow["CountryCode"],Text = (String)oDataRow["CountryName"]};
list.Add(oSelectListItem);
}
ViewData["DDLCountry"] = list;
8. ChildActionOnlyAttribute : Represents an attribute that is used to
indicate that an action method should be called only as a child action.
9. CompareAttribute : Provides an attribute that compares two properties
of a model.
10. CustomModelBinderAttribute : Represents an attribute that invokes a
custom model binder.
11. FilterAttribute : Represents the base class for action and result
filter attributes.
System.Object
System.Attribute
System.Web.Mvc.FilterAttribute
System.Web.Mvc.ActionFilterAttribute
System.Web.Mvc.AuthorizeAttribute
System.Web.Mvc.ChildActionOnlyAttribute
System.Web.Mvc.HandleErrorAttribute
System.Web.Mvc.RequireHttpsAttribute
System.Web.Mvc.ValidateAntiForgeryTokenAttribute
System.Web.Mvc.ValidateInputAttribute
12. HandleErrorAttribute : Represents an attribute that is used to handle
an exception that is thrown by an action method.
13. HiddenInputAttribute : Represents an attribute that is used to
indicate whether a property or field value should be rendered as a hidden
input element.
14. HttpDeleteAttribute : Represents an attribute that is used to
restrict an action method so that the method handles only HTTP DELETE
requests.
15. HttpGetAttribute : Represents an attribute that is used to restrict
an action method so that the method handles only HTTP GET requests.
16. HttpHeadAttribute : Specifies that the HTTP request must be the HTTP
HEAD method.
17. HttpOptionsAttribute : Represents an attribute that is used to
restrict an action method so that the method handles only HTTP OPTIONS
requests.
18, HttpPatchAttribute : Represents an attribute that is used to restrict
an action method so that the method handles only HTTP PATCH requests.
19. HttpPostAttribute : Represents an attribute that is used to restrict
an action method so that the method handles only HTTP POST requests.
20. HttpPutAttribute : Represents an attribute that is used to restrict
an action method so that the method handles only HTTP PUT requests.
21. ModelBinderAttribute : Represents an attribute that is used to
associate a model type to a model-builder type.
22. NoAsyncTimeoutAttribute : Provides a convenience wrapper for the
AsyncTimeoutAttribute attribute.
23. NonActionAttribute : Represents an attribute that is used to indicate
that a controller method is not an action method.
24. OutputCacheAttribute : Represents an attribute that is used to mark
an action method whose output will be cached.
25. RemoteAttribute : Provides an attribute that uses the jQuery
validation plug-in remote validator.
26. RequireHttpsAttribute : Represents an attribute that forces an
unsecured HTTP request to be re-sent over HTTPS.
27. SessionStateAttribute : Specifies the session state of the
controller.
28. ValidateInputAttribute : Represents an attribute that is used to mark
action methods whose input must be validated.
You can write your own attributes by directly or indirectly inheriting from System.Attribute .
For example you can see sample below where MyAFActionFilters in herits ActionFilterAttribute
which again is inherited. Shown Below Inheritance Chain.
System.Attribute
System.Web.Mvc.FilterAttribute
System.Web.Mvc.ActionFilterAttribute
MyAFActionFilters : ActionFilterAttribute
Action Filters are used in cases where we need to perform some logic either before an action
method is called or after an action method runs.
Action Filters : How to use them
Action Filters can be applied to a controller action or an entire controller. The Best known example of
an action filter is the [Authorize] Attribute.
LIST OF ACTION FILTERS
1. OutputCache : This action filter caches the output of a controller
action for a specified amount of time.
2. HandleError : This action filter handles errors raised when a
controller action executes.
3. Authorize : This action filter enables you to restrict access to a
particular user or role.
Action Filters : How to create an Action Filter Filters are custom classes that provide both a declarative and programmatic means to add pre-
action and post-action behavior to controller action methods.
Types of Action Filters
1. Authorization filters Implements the IAuthorizationFilter attribute.
This filter is always executed first.
2. Action filters Implements the IActionFilter attribute.You can use
this filter to modify the viewdata that an action returns.
3. Result filters Implements the IResultFilter attribute. Eg You might
want to modify the view result before view is redered to the browser.
4. Exception filters Implements the IExceptionFilter attribute. Can be
used to log errors, raised by your controller action or controller action
results
Action Filters : Code Sample Writing an Action filter is very simple. All you need is to create a class with Name
WhatEverNameActionFilter
Inherit ActionFilterAttribute class override the action methods and you are done.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Diagnostics;
namespace CampusIndya.Models
{ public class MyAFActionFilters : ActionFilterAttribute
{ public override void OnActionExecuted(ActionExecutedContext
filterContext)
{ MyAF("OnActionExecuting",
filterContext.RouteData); }
public override void OnActionExecuting(ActionExecutingContext
filterContext)
{ base.OnActionExecuting(filterContext); }
public override void OnResultExecuted(ResultExecutedContext
filterContext)
{ base.OnResultExecuted(filterContext); }
public override void OnResultExecuting(ResultExecutingContext
filterContext)
{ base.OnResultExecuting(filterContext); }
private void MyAF(string methodName, RouteData routeData)
{ var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}",
methodName, controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log"); } }}
You can see that in the Solution Explorer the Visual Studio has created some files and folders
Application Information Properties :
References :
Application Folders
App_Data Folder : Used for storing application data
Content Folder : Used for storing static files like
stylesheets icons & images
Scripts Folder : Put the javascript files in here.
By default it contains mvc , ajax &
jquery files.
Models Folder : Contains a Folder for every Controller,
its used to store the view (.cshtml)
files
Views Folder : Contains Model Class which represent
the application models.Model Classes
are used for data manipulation
Controllers Folder : Contains Controller Class which is
responsible for handling user input
and responses
Configuration Files
Global.asax : Its an optional file, This is where u
write logic at the application leavel
or define objects with session or
application
wide scope . Example of practical use
Eg. "Error Handling" .
You can define event handlers in the
application wide or session wide scope.
Packages.confuguration :
Web.config :
Request Flow handles the request from the user ( client ) and send it to the server. Lets look into
details on the function flow internally when client raises a request. This is what happens when u type
an asp .net mvc application URL into the address bar of a web browser & clicks on enter.
Request -->Routing --> Handler -->Controller --> Action --> View --> Response
Detailed Look at the Request Flow
1. Request comes into ASP.NET
2. ASP.NET Routing finds the route match by calling
RouteCollection.GetRouteData
3. This in turn calls RouteBase.GetRouteData on each route until it
finds a match
4. The IRouteHandler for the matching route has its GetHttpHandler
method called
5. The MvcHandler runs (ProcessRequest is called)
6. The MVC controller factory locates and creates the controller in
CreateController
7. The ControllerActionInvoker determines which action to run in
InvokeAction
8. The AuthorizationFilter stage executes (this includes the
authorization method on the controller itself)
9. The ActionExecuting stage executes
10. The requested action method is executed
11. The ActionExecuted stage executes
12. If there is a result object then the ResultExecuting stage executes
13. If the result wasn't cancelled then the ActionResult's
ExecuteResult method is executed
14. The ResultExecuted stage executes
15. If an error occured then the Exception stage executes
Let Look at the Errors
Since the return type is View MVC Does the Following
-> Check to see in the Views -> Home ( Controller Name ) -> Index.aspx,
ascx
( Index is the Action Method Name , Note : if the action methods name
is
hello it would search for hello.aspx)
-> After Checking in the View's Home Folder For Action Method.aspx it
searches the shared folders for view named index.ascx
-> It searches for .cshtml or vbhtml file types in views->controller
folder
followed views->shared
-> finally if the actionmethod.ascx in this case index.ascx is not found
it thows an error like above.
-> the solution to solve the error is simple, just add a vew for the
Controlelrs Action Method
Creating the barebone hello world application with only the routing & controller helps to learn whats
the bare minimum thats required to run an mvc application.
Step 1 : Create A New Project Step 2 : Delete All Selected Files Except Configutatoin ( Global.asax, Web.Config & Packages.Config ) Step 3 : Add New Folder "Controllers"
Step 4 : Add New Controller : "Home Controller"
Step 4 : Change return type to Content
Run the application
The Above Program is the smallest or a breabone program you can write which outputs some text.
As you can see this program has only the Controller and has NO View or Models
NOW A PROGRAM WITH ONLY CONTROLLER & VIEW
Step 1 : Change Return Type to View & Run the Program
Let Look at the Errors
Since the return type is View MVC Does the Following
-> Check to see in the Views -> Home ( Controller Name ) -> Index.aspx,
ascx
( Index is the Action Method Name , Note : if the action methods name
is
hello it would search for hello.aspx)
-> After Checking in the View's Home Folder For Action Method.aspx it
searches the shared folders for view named index.ascx
-> It searches for .cshtml or vbhtml file types in views->controller
folder
followed views->shared
-> finally if the actionmethod.ascx in this case index.ascx is not found
it thows an error like above.
-> the solution to solve the error is simple, just add a vew for the
Controlelrs Action Method
Step 2 : Add A View Page
To do this right click on the action method index
Uncheck everything & Click on add
In the newly careted page . add text to display as shown above
Step 3 : Run the application
Step 4: Modify the program by Passing Data From Controller To View
Step 5 : Run the application
The Above Program is the smallest or a breabone program you can write which outputs some text. As you can see this program has only the Controller and has NO View or Models
NOW A PROGRAM WITH ONE MORE ELEMENT MODEL to create Your Model View Controller Application
Step 1 : Add New Folder ModelsStep 2 : Add New Model Named CountryStep 3 : Add Properties Country Code & Country NameStep 4 : Home Controller Create an Instance of Country , populate data and pass it in ViewStep 5 : Create A Strongly Typed View
We will delete the index in view file as it already exist else it will theow an already exist error
Step 5 : Modify View to Display the object value & Run the application
This is your barebone Hello World Controller Application
LETS MODIFY THE PROGRAM TO DISPLAY A LIST OF COUNTRIES
Step 1 : Modify the Home Controller so that we can data of type List to the ViewStep 2 : Delete Existing Index View & Create A New Stronly Typed View With A Scaffold Template type ListStep 3 : Run the Application Step 4 :Clean Up The View A Bit : Delete SelectedStep 5 : Run the Application
There are different Scaffold Template Types you can use to create the view, This would emilinate the need for us having to write HTML. You can expirement with different Template types.The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.
ASP .NET Routing is setup in two places
Web.Config : ASP .NET Routing is enabled in your web.config file
There are 4 sections in the configuratio file that
are relavent to routing
1. system.web.httpModules section
2. system.web.httpHandlers section
3. system.webserver.modules section
4. system.webserver.handlers section.
Note : Without the above sections the routing will not work, do donot
delete them.
Global.asax : This is a file which contain event handlers for
application life cycle events.
for A Route table is created in the application's global.asax file, which
is created during the applications start event.
Exploring the Global.asax file
In the application Application_Start function we can see a call to RegisterRoutes
You can see a default route map in the figure.
The Route name could be anything unique.
There is a predefined route map which maps to Controller/Action/id
When you add additional routes kindly remember that the order is importnat, they neededs to be
added on top of the default route.
We will add a New Route Search
The Above Route Search/ID maps to Controller = Home/ Action Method = Search / ID
Add Action Method Search To Home Controller
Run the Application
You can define your own custom routes. Remember that the order is important as the the first route
that satisfys the condition is called.
Entity Framrwork ( EF ) is an object relational mapper that enables .Net developers to work with
relational data. It eliminates the need for most of the data access code that the developers need to
write.
What is Entity Framework ?
ADO.NET Entity Framework (EF) is an open source object-relational mapping (ORM) framework for
the .NET Framework.In EF developers work with the data in terms of class, objects and properties
and forget about the underlying database tables & coloumns. In the example code I will show you
how database its tables & coloumns is generated from objects in code. Goal is to reduce the amount
of code and data mantinance for data centric applications.
ADVANTAGES
1. Development with EF is fast and streamlined
2. Less coding required to accomplish complex tasks
3. Database Independant (Free from hardcoded dependencies on a
particular data engine or storage schema)
4. Extensible
5. Mappings between the conceptual model and the storage-specific schema
can change without changing the application code.
6. Developers can work with a consistent application object model that
can be mapped to various storage schemas, possibly implemented in
different database management systems.
7. Multiple conceptual models can be mapped to a single storage schema.
8. Language-integrated query (LINQ) support provides compile-time
syntax validation for queries against a conceptual model.
Entity Framework Architecture