Sunteți pe pagina 1din 101

Setting default submit button

1.
2.
3. <script
4. type="text/javascript"> $(document).ready(function (){
$("#MyForm").keypress(function (e) { kCode = e.keyCode || e.charCode //for cross
browser
5. if (kCode == 13) { var defaultbtn = $(this).attr("DefaultButton");
6. $("#" + defaultbtn).click();
7. return false;
8. }
9. });
10. });
11. </script>
12. @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { DefaultButton =
"SubmitButton", id = "MyForm" }))
13. {
14. @Html.TextBox("txtname")
15. <span>Please Enter value and then press Enter Key</span><br />
16. <input type="submit" name="btnSubmit" id="SubmitButton" value="Submit" />
17. }

In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data
from controller to view and in next request. Like WebForm, you can also use Session to
persist data during a user session. Now question is that when to use ViewData, VieBag,
TempData and Session. Each of them has its own importance. In this article, I am trying to
explain the differences among these four.

ViewData
1. ViewData is a dictionary object that is derived from ViewDataDictionary class.
1. public ViewDataDictionary ViewData { get; set; }
2. ViewData is a property of ControllerBase class.
3. ViewData is used to pass data from controller to corresponding view.
4. It’s life lies only during the current request.
5. If redirection occurs then it’s value becomes null.
6. It’s required typecasting for getting data and check for null values to avoid error.

ViewBag
1. ViewBag is a dynamic property that takes advantage of the new dynamic features in
C# 4.0.
2. Basically it is a wrapper around the ViewData and also used to pass data from
controller to corresponding view.
1. public Object ViewBag { get; }
3. ViewBag is a property of ControllerBase class.
4. It’s life also lies only during the current request.
5. If redirection occurs then it’s value becomes null.
6. It doesn’t required typecasting for getting data.

TempData
1. TempData is a dictionary object that is derived from TempDataDictionary class and
stored in short lives session.
1. public TempDataDictionary TempData { get; set; }
2. TempData is a property of ControllerBase class.
3. TempData is used to pass data from current request to subsequent request (means
redirecting from one page to another).
4. It’s life is very short and lies only till the target view is fully loaded.
5. It’s required typecasting for getting data and check for null values to avoid error.
6. It is used to store only one time messages like error messages, validation messages.
To persist data with TempData refer this article: Persisting Data with TempData

Session
1. In ASP.NET MVC, Session is a property of Controller class whose type is
HttpSessionStateBase.
1. public HttpSessionStateBase Session { get; }
2. Session is also used to pass data within the ASP.NET MVC application and Unlike
TempData, it persists for its expiration time (by default session expiration time is 20
minutes but it can be increased).
3. Session is valid for all requests, not for a single redirect.
4. It’s also required typecasting for getting data and check for null values to avoid error.
In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in
the strongly-typed view. It is used to pass data from controller to strongly-typed view.

Key Points about ViewModel


1. ViewModel contain fields that are represented in the view (for
LabelFor,EditorFor,DisplayFor helpers)
2. ViewModel can have specific validation rules using data annotations or
IDataErrorInfo.
3. ViewModel can have multiple entities or objects from different data models or data
source.

ViewModel Example
Designing ViewModel
1. public class UserLoginViewModel
2. {
3. [Required(ErrorMessage = "Please enter your username")]
4. [Display(Name = "User Name")]
5. [MaxLength(50)]
6. public string UserName { get; set; }
7. [Required(ErrorMessage = "Please enter your password")]
8. [Display(Name = "Password")]
9. [MaxLength(50)]
10. public string Password { get; set; }
11. }

Presenting the viewmodel in the view


1. @model MyModels.UserLoginViewModel
2. @{
3. ViewBag.Title = "User Login";
4. Layout = "~/Views/Shared/_Layout.cshtml";
5. }
6. @using (Html.BeginForm())
7. {
8. <div class="editor-label">
9. @Html.LabelFor(m => m.UserName)
10. </div>
11. <div class="editor-field">
12. @Html.TextBoxFor(m => m.UserName)
13. @Html.ValidationMessageFor(m => m.UserName)
14. </div>
15. <div class="editor-label">
16. @Html.LabelFor(m => m.Password)
17. </div>
18. <div class="editor-field">
19. @Html.PasswordFor(m => m.Password)
20. @Html.ValidationMessageFor(m => m.Password)
21. </div>
22. <p>
23. <input type="submit" value="Log In" />
24. </p>
25. </div>
26. }

Working with Action


1. public ActionResult Login()
2. {
3. return View();
4. }
5. [HttpPost]
6. public ActionResult Login(UserLoginViewModel user)
7. {
8. // To acces data using LINQ
9. DataClassesDataContext mobjentity = new DataClassesDataContext();
10. if (ModelState.IsValid)
11. {
12. try
13. {
14. var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password =
= user.Password).ToList();
15. if (q.Count > 0)
16. {
17. return RedirectToAction("MyAccount");
18. }
19. else
20. {
21. ModelState.AddModelError("", "The user name or password provided is incorrect.");
22. }
23. }
24. catch (Exception ex)
25. {
26. }
27. }
28. return View(user);
29. }

Some Tips for using ViewModel


1. In ViewModel put only those fields/data that you want to display on the view/page.
2. Since view reperesents the properties of the ViewModel, hence it is easy for rendering
and maintenance.
3. Use a mapper when ViewModel become more complex.
In this way, ViewModel help us to organize and manage data in a strongly-typed view
with more flexible way than complex objects like models or ViewBag/ViewData objects.
Data validation is a key aspect for developing web application. In Asp.net MVC, we can
easily apply validation to web application by using Data Annotation attribute classes to
model class. Data Annotation attribute classes are present in
System.ComponentModel.DataAnnotations namespace and are availlable to Asp.net
projects like Asp.net web application & website, Asp.net MVC, Web forms and also to
Entity framework orm models.
Data Annotations help us to define the rules to the model classes or properties for data
validation and displaying suitable messages to end users.

Data Annotation Validator Attributes


1. DataType
Specify the datatype of a property

2. DisplayName
specify the display name for a property.

3. DisplayFormat
specify the display format for a property like different format for Date proerty.

4. Required
Specify a property as required.

5. ReqularExpression
validate the value of a property by specified regular expression pattern.

6. Range
validate the value of a property with in a specified range of values.

7. StringLength
specify min and max length for a string property.
8. MaxLength
specify max length for a string property.

9. Bind
specify fields to include or exclude when adding parameter or form values to model
properties.

10. ScaffoldColumn
specify fields for hiding from editor forms.

Designing the model with Data Annotations


1.
2. using System.ComponentModel;
3. using System.ComponentModel.DataAnnotations;
4. using System.Web.Mvc;
5. namespace Employee.Models
6. {
7. [Bind(Exclude = "EmpId")]
8. public class Employee
9. {
10. [ScaffoldColumn(false)]
11. public int EmpId { get; set; }
12.
13. [DisplayName("Employee Name")]
14. [Required(ErrorMessage = "Employee Name is required")]
15. [StringLength(100,MinimumLength=3)]
16. public String EmpName { get; set; }
17.
18. [Required(ErrorMessage = "Employee Address is required")]
19. [StringLength(300)]
20. public string Address { get; set; }
21.
22. [Required(ErrorMessage = "Salary is required")]
23. [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
24. public int Salary{ get; set; }
25.
26. [Required(ErrorMessage = "Please enter your email address")]
27. [DataType(DataType.EmailAddress)]
28. [Display(Name = "Email address")]
29. [MaxLength(50)]
30. [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Plea
se enter correct email")]
31. public string Email { get; set; }
32. }
33. }
Once we have define validation to the model by using data annotations, these are
automatically used by Html Helpers in views. For client side validation to work, please
ensure that below two <SCRIPT> tag references are in the view.
1. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascri
pt"></script>
2. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="te
xt/javascript"></script>

Presenting the model in the view


1. @model Employee.Models
2. @{
3. ViewBag.Title = "Employee Details";
4. Layout = "~/Views/Shared/_Layout.cshtml";
5. }
6. @using (Html.BeginForm())
7. {
8. <div class="editor-label">
9. @Html.LabelFor(m => m.EmpName)
10. </div>
11. <div class="editor-field">
12. @Html.TextBoxFor(m => m.EmpName)
13. @Html.ValidationMessageFor(m => m.EmpName)
14. </div>
15. <div class="editor-label">
16. @Html.LabelFor(m => m.Address)
17. </div>
18. <div class="editor-field">
19. @Html.TextBoxFor(m => m.Address)
20. @Html.ValidationMessageFor(m => m.Address)
21. </div>
22. <div class="editor-label">
23. @Html.LabelFor(m => m.Salary)
24. </div>
25. <div class="editor-field">
26. @Html.TextBoxFor(m => m.Salary)
27. @Html.ValidationMessageFor(m => m.Salary)
28. </div>
29. <div class="editor-label">
30. @Html.LabelFor(m => m.Email)
31. </div>
32. <div class="editor-field">
33. @Html.TextBoxFor(m => m.Email)
34. @Html.ValidationMessageFor(m => m.Email)
35. </div>
36. <p> <input type="submit" value="Save" />
37. </p>
38. }
By default MVC is configured to resolve a view by searching the views that match the Web
Form view engine's naming conventions first. After that MVC begins search for the views
that match the Razor view engine's naming conventions as shown in below fig.
So, If are not using ASPX views in your MVC applications then the checking four unused
locations first for every return View() and Html.RenderPartial is quite wasteful and time
consuming. After removing Web Form engine, Razor View Engine will be almost twice as
fast with the Web Form engine.

Removing the Web Form (ASPX) view engine


Removing the Web Form view engine is easy in MVC. We can remove all the view engines
and add only Razor view engine by using Application_Start event of Global.asax.cs file like
as:
1. protected void Application_Start()
2. {
3. //Remove All Engine
4. ViewEngines.Engines.Clear();
5. //Add Razor Engine
6. ViewEngines.Engines.Add(new RazorViewEngine());
7. ...
8. }
After removing all the view engines and register only Razor view engine, now MVC try to
resolve a view by searching the views that match the Razor view engine's naming
conventions only as shown in fig.
You can also make your custom View Engine. For help refer the article Custom Razor View
Engine for C# and VB

Note
1. After removing Web Form engine, Razor View Engine will be almost twice as fast with the
Web Form engine.
2. Use this when you are sure that you will use only Razor views. It will be helpful to you.
3. If you are using both type of views (ASPX & Razor), don't implement this.

Asp.net MVC Request Life Cycle


While programming with Asp.net MVC, you should be aware of the life of an Asp.net MVC
request from birth to death. In this article, I am going to expose the Asp.net MVC Request
Life cycle. There are seven main steps that happen when you make a request to an Asp.net
MVC web applications. For more details refer Detailed ASP.NET MVC Pipeline

1. Routing
Asp.net Routing is the first step in MVC request cycle. Basically it is a pattern matching
system that matches the request’s URL against the registered URL patterns in the
Route Table. When a matching pattern found in the Route Table, the Routing engine
forwards the request to the corresponding IRouteHandler for that request. The
default one calls the MvcHandler. The routing engine returns a 404 HTTP status code
against that request if the patterns is not found in the Route Table.
When application starts at first time, it registers one or more patterns to the Route
Table to tell the routing system what to do with any requests that match these
patterns. An application has only one Route Table and this is setup in the Global.asax
file of the application.
1. public static void RegisterRoutes(RouteCollection routes)
2. {
3. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
4. routes.MapRoute( "Default", // Route name
5. "{controller}/{action}/{id}", // URL with parameters
6. new { controller = "Home", action = "Index", id = UrlParameter.Op
tional } // Parameter defaults
7. );
8. }
2. MvcHandler
The MvcHandler is responsible for initiating the real processing inside ASP.NET MVC.
MVC handler implements IHttpHandler interface and further process the request by
using ProcessRequest method as shown below:
1. protected internal virtual void ProcessRequest(HttpContextBase htt
pContext)
2. {
3. SecurityUtil.ProcessInApplicationTrust(delegate {
4. IController controller;
5. IControllerFactory factory;
6. this.ProcessRequestInit(httpContext, out controller, out factory)
;
7. try
8. {
9. controller.Execute(this.RequestContext);
10. }
11. finally
12. {
13. factory.ReleaseController(controller);
14. }
15. });
16. }

3. Controller
As shown in above code, MvcHandler uses the IControllerFactory instance and tries
to get a IController instance. If successful, the Execute method is called. The
IControllerFactory could be the default controller factory or a custom factory
initialized at the Application_Start event, as shown below:
1. protected void Application_Start()
2. {
3. AreaRegistration.RegisterAllAreas();
4. RegisterRoutes(RouteTable.Routes);
5. ControllerBuilder.Current.SetControllerFactory(new CustomControll
erFactory());
6. }

4. Action Execution
Once the controller has been instantiated, Controller's ActionInvoker determines
which specific action to invoke on the controller. Action to be execute is chosen based
on attributes ActionNameSelectorAttribute (by default method which have the
same name as the action is chosen) and ActionMethodSelectorAttribute(If more
than one method found, the correct one is chosen with the help of this attribute).

5. View Result
The action method receives user input, prepares the appropriate response data, and
then executes the result by returning a result type. The result type can be ViewResult,
RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and
EmptyResult.

6. View Engine
The first step in the execution of the View Result involves the selection of the
appropriate View Engine to render the View Result. It is handled
by IViewEngine interface of the view engine. By default Asp.Net MVC
uses WebForm and Razor view engines. You can also register your own custom view
engine to your Asp.Net MVC application as shown below:
1. protected void Application_Start()
2. {
3. //Remove All View Engine including Webform and Razor
4. ViewEngines.Engines.Clear();
5. //Register Your Custom View Engine
6. ViewEngines.Engines.Add(new CustomViewEngine());
7. //Other code is removed for clarity
8. }

7. View
Action method may returns a text string,a binary file or a Json formatted data. The
most important Action Result is the ViewResult, which renders and returns an HTML
page to the browser by using the current view engine.

auhan Print
05 Jan 2013
06 Aug 2018
Advanced
218K
Caching is a most important aspect of high-performance web application. Caching
provides a way of storing frequently accessed data and reusing that data. Practically, this
is an effective way for improving web application’s performance.
Advantage of Caching
1. Reduce hosting server round-trips
When content is cached at the client or in proxies, it cause minimum request to server.

2. Reduce database server round-trips


When content is cached at the web server, it can eliminate the database request.

3. Reduce network traffic


When content is cached at the client side, it it also reduce the network traffic.

4. Avoid time-consumption for regenerating reusable


content
When reusable content is cached, it avoid the time consumption for regenerating
reusable content.

5. Improve performance
Since cached content reduce round-trips, network traffic and avoid time
consumption for regenerating reusable content which cause a boost in the
performance.

Key points about Caching


1. Use caching for contents that are accessed frequently.
2. Avoid caching for contents that are unique per user.
3. Avoid caching for contents that are accessed infrequently/rarely.
4. Use the VaryByCustom function to cache multiple versions of a page based on
customization aspects of the request such as cookies, role, theme, browser, and so
on.
5. For efficient caching use 64-bit version of Windows Server and SQL Server.
6. For database caching make sure your database server has sufficient RAM otherwise,
it may degrade the performance.
7. For caching of dynamic contents that change frequently, define a short cache–
expiration time rather than disabling caching.
Output Cache Filter
The OutputCache filter allow you to cache the data that is output of an action method. By
default, this attribute filter cache the data till 60 seconds. After 60 sec, if a call was made
to this action then ASP.NET MVC will cache the output again.

Enabling Output Caching


You can enable the output caching for an action method or controller by adding an
[OutputCache] attribute as shown below:
1. [OutputCache(Duration=20, VaryByParam="none")]
2. public ActionResult Index()
3. {
4. ViewBag.Message = DateTime.Now.ToString();
5. return View();
6. }
The output of the Index() action method will be cached for 20 seconds. If you will not
defined the duration, it will cached it for by default cache duration 60 sec. You can see
the cache effect by applying the break point on index method as shown below.

OutputCache Filter Parameter


Parameter
Type
Description
CacheProfile
string
Specify the name of the output cache policy which is defined with in
<outputCacheSettings> tag of Web.config.
Duration
int
Specify the time in sec to cache the content
Location
OutputCacheLocation
Specify the location of the output to be cached. By default location is Any.
NoStore
bool
Enable/Disable where to use HTTP Cache-Control. This is used only to protect very
sensitive data.
SqlDependency
string
Specify the database and table name pairs on which the cache content depends on. The
cached data will expire automatically when the data changes in the database.
VaryByContentEncoding
string
Specify the semicolon separated list of character set (Content encoding like gzip and
deflate) that the output cache uses to vary the cache content
VaryByCustom
string
Specify the list of custom strings that the output cache uses to vary the cache content.
VaryByHeader
string
Specify the semicolon separated list of HTTP header names that are used to vary the
cache content.
VaryByParam
string
Specify the semicolon separated list of form POST or query string parameters that are
used to vary the cache content. If not specified, the default value is none.

Output Caching Location


By default, content is cached in three locations: the web server, any proxy servers, and the
user's browser. You can control the content's cached location by changing the location
parameter of the OutputCache attribute to any of the following values: Any, Client,
Downstream, Server, None, or ServerAndClient.
By default, the location parameter has the value Any which is appropriate for most the
scenarios. But there are scenarios when you required more control over the cached data.
Suppose you want to cache the logged in use information then you should cache the data
on client browser since this data is specific to a user. If you will cache this data on the
server, all the user will see the same information that is wrong.
You should cache the data on the server which is common to all the users and is sensitive.

Configure Cache Location


For configuring the cache location, you need to add the System.Web.UI namespace on
your controller. You can cached the user's personal information in his browser like as
below.
1. [OutputCache(Duration = 7200, Location = OutputCacheLocation.Client, VaryByParam = "
none", NoStore = true)]
2. public ActionResult Index()
3. {
4. ViewBag.Message = "Welcome : " + User.Identity.Name;
5. return View();
6. }

Authorization is the process of determining the rights of an authenticated user for


accessing the application's resources. The Asp.Net MVC Framework has a
AuthorizeAttribute filter for filtering the authorized user to access a resource. Refer this
article for Custom Authentication and Authorization in ASP.NET MVC
Authorize Attribute Properties
Properties
Description
Roles
Gets or sets the roles required to access the controller or action method.
Users
Gets or sets the user names required to access the controller or action method.

Filtering Users by Users Property


Suppose you want to allow the access of AdminProfile to only shailendra and mohan users
then you can specify the authorize users list to Users property as shown below.
1. [Authorize(Users = "shailendra,mohan")]
2. public ActionResult AdminProfile()
3. {
4. return View();
5. }
Filtering Users by Roles Property
Suppose you want to allow the access of AdminProfile action to only Admin and
SubAdmin roles then you can specify the authorize roles list to Users property as shown
below.
1. [Authorize(Roles = "Admin,SubAdmin")]
2. public ActionResult AdminProfile()
3. {
4. return View();
5. }

When standard types of authentication do not meet your requirements, you need to
modify an authentication mechanism to create a custom solution. A user context has a
principal which represents the identity and roles for that user. A user is authenticated by
its identity and assigned roles to a user determine about authorization or permission to
access resources.

ASP.NET provides IPrincipal and IIdentity interfaces to represents the identity and role for
a user. You can create a custom solution by evaluating the IPrincipal and IIdentity
interfaces which are bound to the HttpContext as well as the current thread.
1. public class CustomPrincipal : IPrincipal
2. {
3. public IIdentity Identity { get; private set; }
4. public bool IsInRole(string role)
5. {
6. if (roles.Any(r => role.Contains(r)))
7. {
8. return true;
9. }
10. else
11. {
12. return false;
13. }
14. }
15.
16. public CustomPrincipal(string Username)
17. {
18. this.Identity = new GenericIdentity(Username);
19. }
20.
21. public int UserId { get; set; }
22. public string FirstName { get; set; }
23. public string LastName { get; set; }
24. public string[] roles { get; set; }
25. }
Now you can put this CustomPrincipal objects into the thread’s currentPrinciple property
and into the HttpContext’s User property to accomplish your custom authentication and
authorization process.

ASP.NET Forms Authentication


ASP.NET forms authentication occurs after IIS authentication is completed. You can
configure forms authentication by using forms element with in web.config file of your
application. The default attribute values for forms authentication are shown below:
1. <system.web>
2. <authentication mode="Forms">
3. <forms loginUrl="Login.aspx"
4. protection="All"
5. timeout="30"
6. name=".ASPXAUTH"
7. path="/"
8. requireSSL="false"
9. slidingExpiration="true"
10. defaultUrl="default.aspx"
11. cookieless="UseDeviceProfile"
12. enableCrossAppRedirects="false" />
13. </authentication>
14. </system.web>
The FormsAuthentication class creates the authentication cookie automatically when
SetAuthCookie() or RedirectFromLoginPage() methods are called. The value of
authentication cookie contains a string representation of the encrypted and signed
FormsAuthenticationTicket object.
You can create the FormsAuthenticationTicket object by specifying the cookie name,
version of the cookie, directory path, issue date of the cookie, expiration date of the
cookie, whether the cookie should be persisted, and optionally user-defined data as
shown below:
1. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
2. "userName",
3. DateTime.Now,
4. DateTime.Now.AddMinutes(30), // value of time out property
5. false, // Value of IsPersistent property
6. String.Empty,
7. FormsAuthentication.FormsCookiePath);
Now, you can encrypt this ticket by using the Encrypt method FormsAuthentication class
as given below:
1. string encryptedTicket = FormsAuthentication.Encrypt(ticket);

Note
To encrypt FormsAuthenticationTicket ticket set the protection attribute of the forms
element to All or Encryption.
Custom Authorization
ASP.NET MVC provides Authorization filter to authorize a user. This filter can be applied
to an action, a controller, or even globally. This filter is based on AuthorizeAttribute class.
You can customize this filter by overriding OnAuthorization() method as shown below:
1. public class CustomAuthorizeAttribute : AuthorizeAttribute
2. {
3. public string UsersConfigKey { get; set; }
4. public string RolesConfigKey { get; set; }
5.
6. protected virtual CustomPrincipal CurrentUser
7. {
8. get { return HttpContext.Current.User as CustomPrincipal; }
9. }
10.
11. public override void OnAuthorization(AuthorizationContext filterContext)
12. {
13. if (filterContext.HttpContext.Request.IsAuthenticated)
14. {
15. var authorizedUsers = ConfigurationManager.AppSettings[UsersConfigKey];
16. var authorizedRoles = ConfigurationManager.AppSettings[RolesConfigKey];
17.
18. Users = String.IsNullOrEmpty(Users) ? authorizedUsers : Users;
19. Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;
20.
21. if (!String.IsNullOrEmpty(Roles))
22. {
23. if (!CurrentUser.IsInRole(Roles))
24. {
25. filterContext.Result = new RedirectToRouteResult(new
26. RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
27.
28. // base.OnAuthorization(filterContext); //returns to login url
29. }
30. }
31.
32. if (!String.IsNullOrEmpty(Users))
33. {
34. if (!Users.Contains(CurrentUser.UserId.ToString()))
35. {
36. filterContext.Result = new RedirectToRouteResult(new
37. RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
38.
39. // base.OnAuthorization(filterContext); //returns to login url
40. }
41. }
42. }
43.
44. }
45. }
User Authentication
A user will be authenticated if IsAuthenticated property returns true. For authenticating a
user you can use one of the following two ways:
1. Thread.CurrentPrincipal.Identity.IsAuthenticated
2. HttpContext.Current.User.Identity.IsAuthenticated

Designing Data Model


Now it’s time to create data access model classes for creating and accessing Users and
Roles as shown below:
1. public class User
2. {
3. public int UserId { get; set; }
4.
5. [Required]
6. public String Username { get; set; }
7.
8. [Required]
9. public String Email { get; set; }
10.
11. [Required]
12. public String Password { get; set; }
13.
14. public String FirstName { get; set; }
15. public String LastName { get; set; }
16.
17. public Boolean IsActive { get; set; }
18. public DateTime CreateDate { get; set; }
19.
20. public virtual ICollection<Role> Roles { get; set; }
21. }
1. public class Role
2. {
3. public int RoleId { get; set; }
4.
5. [Required]
6. public string RoleName { get; set; }
7. public string Description { get; set; }
8.
9. public virtual ICollection<User> Users { get; set; }
10. }

Defining Database Context with code first


mapping between User and Role
Using Entity Framework code first approach, create a DataContext having User and Role
entities with its relational mapping details as shown below:
1. public class DataContext : DbContext
2. {
3. public DataContext()
4. : base("DefaultConnection")
5. {
6.
7. }
8. protected override void OnModelCreating(DbModelBuilder modelBuilder)
9. {
10. modelBuilder.Entity<User>()
11. .HasMany(u => u.Roles)
12. .WithMany(r=>r.Users)
13. .Map(m =>
14. {
15. m.ToTable("UserRoles");
16. m.MapLeftKey("UserId");
17. m.MapRightKey("RoleId");
18. });
19. }
20. public DbSet<User> Users { get; set; }
21. public DbSet<Role> Roles { get; set; }
22. }

Code First Database Migrations


With the help of entity framework code first database migrations create the database
named as Security in the SQL Server. Run the following command through Visual Studio
Package Manager Console to migrate your code into SQL Server database.

After running first command i.e. enabling migrations for your project, add seed data to
Configuration.cs file of Migrations folder as shown below:
1. protected override void Seed(Security.DAL.DataContext context)
2. {
3. Role role1 = new Role { RoleName = "Admin" };
4. Role role2 = new Role { RoleName = "User" };
5.
6. User user1 = new User { Username = "admin", Email = "admin@ymail.com", FirstName =
"Admin", Password = "123456", IsActive = true, CreateDate = DateTime.UtcNow, Roles =
new List() };
7.
8. User user2 = new User { Username = "user1", Email = "user1@ymail.com", FirstName =
"User1", Password = "123456", IsActive = true, CreateDate = DateTime.UtcNow, Roles =
new List() };
9.
10. user1.Roles.Add(role1);
11. user2.Roles.Add(role2);
12.
13. context.Users.Add(user1);
14. context.Users.Add(user2);
15. }
When above three commands will be executed successfully as shown above, the following
database will be created in your SQL Server.

Solution Structure
Designing View Model
Create a view model class for handing login process as given below:
1. public class LoginViewModel
2. {
3. [Required]
4. [Display(Name = "User name")]
5. public string Username { get; set; }
6.
7. [Required]
8. [DataType(DataType.Password)]
9. [Display(Name = "Password")]
10. public string Password { get; set; }
11.
12. [Display(Name = "Remember me?")]
13. public bool RememberMe { get; set; }
14. }
15.
1. public class CustomPrincipalSerializeModel
2. {
3. public int UserId { get; set; }
4. public string FirstName { get; set; }
5. public string LastName { get; set; }
6. public string[] roles { get; set; }
7. }

Forms Authentication Initialization


1. public class AccountController : Controller
2. {
3. DataContext Context = new DataContext();
4. //
5. // GET: /Account/
6. public ActionResult Index()
7. {
8. return View();
9. }
10.
11. [HttpPost]
12. public ActionResult Index(LoginViewModel model, string returnUrl = "")
13. {
14. if (ModelState.IsValid)
15. {
16. var user = Context.Users.Where(u => u.Username == model.Username && u.Password == m
odel.Password).FirstOrDefault();
17. if (user != null)
18. {
19. var roles=user.Roles.Select(m => m.RoleName).ToArray();
20.
21. CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel()
;
22. serializeModel.UserId = user.UserId;
23. serializeModel.FirstName = user.FirstName;
24. serializeModel.LastName = user.LastName;
25. serializeModel.roles = roles;
26.
27. string userData = JsonConvert.SerializeObject(serializeModel);
28. FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
29. 1,
30. user.Email,
31. DateTime.Now,
32. DateTime.Now.AddMinutes(15),
33. false, //pass here true, if you want to implement remember me functionality
34. userData);
35.
36. string encTicket = FormsAuthentication.Encrypt(authTicket);
37. HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicke
t);
38. Response.Cookies.Add(faCookie);
39.
40. if(roles.Contains("Admin"))
41. {
42. return RedirectToAction("Index", "Admin");
43. }
44. else if (roles.Contains("User"))
45. {
46. return RedirectToAction("Index", "User");
47. }
48. else
49. {
50. return RedirectToAction("Index", "Home");
51. }
52. }
53.
54. ModelState.AddModelError("", "Incorrect username and/or password");
55. }
56.
57. return View(model);
58. }
59.
60. [AllowAnonymous]
61. public ActionResult LogOut()
62. {
63. FormsAuthentication.SignOut();
64. return RedirectToAction("Login", "Account", null);
65. }
66. }
67.
1. public class MvcApplication : System.Web.HttpApplication
2. {
3. protected void Application_Start()
4. {
5. AreaRegistration.RegisterAllAreas();
6.
7. WebApiConfig.Register(GlobalConfiguration.Configuration);
8. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
9. RouteConfig.RegisterRoutes(RouteTable.Routes);
10. BundleConfig.RegisterBundles(BundleTable.Bundles);
11.
12. Database.SetInitializer<DataContext>(new DataContextInitilizer());
13. }
14. protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
15. {
16. HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
17. if (authCookie != null)
18. {
19.
20. FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Valu
e);
21.
22. CustomPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject<Custo
mPrincipalSerializeModel>(authTicket.UserData);
23. CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
24. newUser.UserId = serializeModel.UserId;
25. newUser.FirstName = serializeModel.FirstName;
26. newUser.LastName = serializeModel.LastName;
27. newUser.roles = serializeModel.roles;
28.
29. HttpContext.Current.User = newUser;
30. }
31.
32. }
33. }

Base Controller for accessing Current User


Create a base controller for accessing your User data in your all controller. Inherit, your all
controller from this base controller to access user information from the UserContext.
1. public class BaseController : Controller
2. {
3. protected virtual new CustomPrincipal User
4. {
5. get { return HttpContext.User as CustomPrincipal; }
6. }
7. }
1. public class HomeController : BaseController
2. {
3. //
4. // GET: /Home/
5. public ActionResult Index()
6. {
7. string FullName = User.FirstName + " " + User.LastName;
8. return View();
9. }
10. }

Base View Page for accessing Current User


Create a base class for all your views for accessing your User data in your all views as
shown below:
1. public abstract class BaseViewPage : WebViewPage
2. {
3. public virtual new CustomPrincipal User
4. {
5. get { return base.User as CustomPrincipal; }
6. }
7. }
8. public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
9. {
10. public virtual new CustomPrincipal User
11. {
12. get { return base.User as CustomPrincipal; }
13. }
14. }
Register this class with in the \Views\Web.config as base class for all your views as given
below:
1. <system.web.webPages.razor>
2. <!--Other code has been removed for clarity-->
3. <pages pageBaseType="Security.DAL.Security.BaseViewPage">
4. <namespaces>
5. <!--Other code has been removed for clarity-->
6. </namespaces>
7. </pages>
8. </system.web.webPages.razor>
Now you can access the authenticated user information on all your view in easy and
simple way as shown below in Admin View:
1. @{
2. ViewBag.Title = "Index";
3. Layout = "~/Views/Shared/_AdminLayout.cshtml";
4. }
5. <h4>Welcome : @User.FirstName</h4>
6. <h1>Admin DashBoard</h1>

Login View
1. @model Security.Models.LoginViewModel
2.
3. @{
4. ViewBag.Title = "Index";
5. }
6.
7. @using (Html.BeginForm())
8. {
9. @Html.AntiForgeryToken()
10.
11. <div class="form-horizontal">
12. <h4>User Login</h4>
13. <hr />
14. @Html.ValidationSummary(true)
15.
16. <div class="form-group">
17. @Html.LabelFor(model => model.Username, new { @class = "control-label col-md-2" })
18. <div class="col-md-10">
19. @Html.EditorFor(model => model.Username)
20. @Html.ValidationMessageFor(model => model.Username)
21. </div>
22. </div>
23.
24. <div class="form-group">
25. @Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })
26. <div class="col-md-10">
27. @Html.EditorFor(model => model.Password)
28. @Html.ValidationMessageFor(model => model.Password)
29. </div>
30. </div>
31.
32. <div class="form-group">
33. @Html.LabelFor(model => model.RememberMe, new { @class = "control-label col-md-2" }
)
34. <div class="col-md-10">
35. @Html.EditorFor(model => model.RememberMe)
36. @Html.ValidationMessageFor(model => model.RememberMe)
37. </div>
38. </div>
39.
40. <div class="form-group">
41. <div class="col-md-offset-2 col-md-10">
42. <input type="submit" value="Login" class="btn btn-default" />
43. </div>
44. </div>
45. </div>
46. }

Applying CustomAuthorize attribute


To make secure your admin or user pages, decorate your Admin and User controllers with
CustomAuthorize attribute as defined above and specify the uses or roles to access admin
and user pages.
1. [CustomAuthorize(Roles= "Admin")]
2. // [CustomAuthorize(Users = "1")]
3. public class AdminController : BaseController
4. {
5. //
6. // GET: /Admin/
7. public ActionResult Index()
8. {
9. return View();
10. }
11. }
1.
2. [CustomAuthorize(Roles= "User")]
3. // [CustomAuthorize(Users = "1,2")]
4. public class UserController : BaseController
5. {
6. //
7. // GET: /User/
8. public ActionResult Index()
9. {
10. return View();
11. }
12. }
You can also specify the Roles and Users with in your web.config as a key to avoid hard
code values for Users and Roles at the controller level.
1. <add key="RolesConfigKey" value="Admin"/>
2. <add key="UsersConfigKey" value="2,3"/>
Use one of these keys within the CustomAuthorize attribute as shown below:
1. //[CustomAuthorize(RolesConfigKey = "RolesConfigKey")]
2. [CustomAuthorize(UsersConfigKey = "UsersConfigKey")]
3.
4. public class AdminController : BaseController
5. {
6. //
7. // GET: /Admin/
8. public ActionResult Index()
9. {
10. return View();
11. }
12. }
1. [CustomAuthorize(RolesConfigKey = "RolesConfigKey")]
2. // [CustomAuthorize(UsersConfigKey = "UsersConfigKey")]
3. public class UserController : BaseController
4. {
5. //
6. // GET: /User/
7. public ActionResult Index()
8. {
9. return View();
10. }
11. }

Test your application


When you will run your application and will login into the application using user1, you will
be redirected to User dashboard as shown below:
When user will try to access unauthorized pages such as Admin dashboard using URL:
http://localhost:11681/Admin , he will get the custom error page as shown below:

ASP.NET MVC is an open source framework built on the top of Microsoft .NET Framework
to develop the web application that enables a clean separation of code. ASP.NET MVC
framework is the most customizable and extensible platform shipped by Microsoft. In this
article, you will learn the detailed pipeline of ASP.NET MVC.

Routing
Routing is the first step in ASP.NET MVC pipeline. typically, it is a pattern matching system
that matches the incoming request to the registered URL patterns in the Route Table.
The UrlRoutingModule(System.Web.Routing.UrlRoutingModule) is a class which matches
an incoming HTTP request to a registered route pattern in the
RouteTable(System.Web.Routing.RouteTable).
When ASP.NET MVC application starts at first time, it registers one or more patterns to
the RouteTable to tell the routing system what to do with any requests that match these
patterns. An application has only one RouteTable and this is setup in the Application_Start
event of Global.asax of the application.
1. public class RouteConfig
2. {
3. public static void RegisterRoutes(RouteCollection routes)
4. {
5. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
6.
7. routes.MapRoute(
8. name: "Default",
9. url: "{controller}/{action}/{id}",
10. defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
11. );
12. }
13. }
1. protected void Application_Start()
2. {
3. //Other code is removed for clarity
4. RouteConfig.RegisterRoutes(RouteTable.Routes);
5. }
When the UrlRoutingModule finds a matching route within RouteCollection
(RouteTable.Routes), it retrieves the IRouteHandler(System.Web.Mvc.IRouteHandler)
instance(default is System.Web.MvcRouteHandler) for that route. From the route handler,
the module gets an IHttpHandler(System.Web.IHttpHandler) instance(default is
System.Web.MvcHandler).
1. public interface IRouteHandler
2. {
3. IHttpHandler GetHttpHandler(RequestContext requestContext);
4. }
Controller Initialization
The MvcHandler initiates the real processing inside ASP.NET MVC pipeline by using
ProcessRequest method. This method uses the IControllerFactory instance (default is
System.Web.Mvc.DefaultControllerFactory) to create corresponding controller.
1. protected internal virtual void ProcessRequest(HttpContextBase httpContext)
2. {
3. SecurityUtil.ProcessInApplicationTrust(delegate {
4. IController controller;
5. IControllerFactory factory;
6. this.ProcessRequestInit(httpContext, out controller, out factory);
7. try
8. {
9. controller.Execute(this.RequestContext);
10. }
11. finally
12. {
13. factory.ReleaseController(controller);
14. }
15. });
16. }

Action Execution
1. When the controller is initialized, the controller calls its own InvokeAction() method
by passing the details of the chosen action method. This is handled by the
IActionInvoker.
1. public virtual bool InvokeAction(ControllerContext controllerConte
xt, string actionName)
2. After chosen of appropriate action method, model binders(default is
System.Web.Mvc.DefaultModelBinder) retrieves the data from incoming HTTP
request and do the data type conversion, data validation such as required or date
format etc. and also take care of input values mapping to that action method
parameters.
3. Authentication Filter was introduced with ASP.NET MVC5 that run prior to
authorization filter. It is used to authenticate a user. Authentication filter process user
credentials in the request and provide a corresponding principal. Prior to ASP.NET
MVC5, you use authorization filter for authentication and authorization to a user.
By default, Authenticate attribute is used to perform Authentication. You can easily
create your own custom authentication filter by implementing IAuthenticationFilter.
4. Authorization filter allow you to perform authorization process for an authenticated
user. For example, Role based authorization for users to access resources.
By default, Authorize attribute is used to perform authorization. You can also make
your own custom authorization filter by implementing IAuthorizationFilter.
5. Action filters are executed before(OnActionExecuting) and after(OnActionExecuted)
an action is executed. IActionFilter interface provides you two methods
OnActionExecuting and OnActionExecuted methods which will be executed before
and after an action gets executed respectively. You can also make your own custom
ActionFilters filter by implementing IActionFilter. For more about filters refer this
article Understanding ASP.NET MVC Filters and Attributes
6. When action is executed, it process the user inputs with the help of model (Business
Model or Data Model) and prepare Action Result.

Result Execution
1. Result filters are executed before(OnResultnExecuting) and after(OnResultExecuted)
the ActionResult is executed. IResultFilter interface provides you two methods
OnResultExecuting and OnResultExecuted methods which will be executed before
and after an ActionResult gets executed respectively. You can also make your own
custom ResultFilters filter by implementing IResultFilter.
2. Action Result is prepared by performing operations on user inputs with the help of
BAL or DAL. The Action Result type can be ViewResult, PartialViewResult,
RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and
EmptyResult.
Various Result type provided by the ASP.NET MVC can be categorized into two
category- ViewResult type and NonViewResult type. The Result type which renders
and returns an HTML page to the browser, falls into ViewResult category and other
result type which returns only data either in text format, binary format or a JSON
format, falls into NonViewResult category.

View Initialization and Rendering


1. ViewResult type i.e. view and partial view are represented by
IView(System.Web.Mvc.IView) interface and rendered by the appropriate View
Engine.
1. public interface IView
2. {
3. void Render(ViewContext viewContext, TextWriter writer);
4. }
2. This process is handled by IViewEngine(System.Web.Mvc.IViewEngine) interface of
the view engine. By default ASP.NET MVC provides WebForm and Razor view engines.
You can also create your custom engine by using IViewEngine interface and can
registered your custom view engine in to your Asp.Net MVC application as shown
below:
1. protected void Application_Start()
2. {
3. //Remove All View Engine including Webform and Razor
4. ViewEngines.Engines.Clear();
5. //Register Your Custom View Engine
6. ViewEngines.Engines.Add(new CustomViewEngine());
7. //Other code is removed for clarity
8. }
3. Html Helpers are used to write input fields, create links based on the routes, AJAX-
enabled forms, links and much more. Html Helpers are extension methods of the
HtmlHelper class and can be further extended very easily. In more complex scenario,
it might render a form with client side validation with the help of JavaScript or jQuery.
In this article you will learn how to use the repository pattern for CRUD operations and
how to combine it with the unit of work patterns. Before going to write the code, let's
understand the repository and unit of work patterns separately.

Repository Pattern
The repository pattern is used to create an abstraction layer between the DAL (data access
layer) and the BAL (business access layer) to perform CRUD operations.

Repository Pattern Implementation


The repository pattern can be implemented by using following two method :

1. Generic Repository Pattern

A generic repository implementation is used to define common database operations


(like Create, Retrieve Update, Delete etc.) for all the database entities in a single class.
1. public interface IRepository where TEntity : class
2. {
3. IEnumerable GetAll();
4. IEnumerable Find(Expression<func> predicate);</func
5. <func TEntity Get(object Id);</func
6. <func</func
7. <func void Add(TEntity entity);</func
8. <func void AddRange(IEnumerable entities);</func
9. <func</func
10. <func void Update(TEntity entity);</func
11. <func</func
12. <func void Remove(object Id);</func
13. <func void Remove(TEntity entity);</func
14. <func void RemoveRange(IEnumerable entities);</func
15. <func}</func
16. <func</func
17. <func// implementation</func
18. <funcpublic class Repository : IRepository where TEntity : class
</func
19. <func{</func
20. <func protected readonly DbContext db;</func
21. <func</func
22. <func public Repository(DbContext _db)</func
23. <func {</func
24. <func db = _db;</func
25. <func }</func
26. <func</func
27. <func public IEnumerable GetAll()</func
28. <func {</func
29. <func return db.Set().ToList();</func
30. <func }</func
31. <func</func
32. <func public IEnumerable Find(Expression<func> predicate)</func<
/func
33. <func<func {</func</func
34. <func<func return db.Set().Where(predicate);</func</func
35. <func<func }</func</func
36. <func<func</func</func
37. <func<func public TEntity Get(object Id)</func</func
38. <func<func {</func</func
39. <func<func return db.Set().Find(Id);</func</func
40. <func<func }</func</func
41. <func<func</func</func
42. <func<func public void Add(TEntity entity)</func</func
43. <func<func {</func</func
44. <func<func db.Set().Add(entity);</func</func
45. <func<func }</func</func
46. <func<func</func</func
47. <func<func public void AddRange(IEnumerable entities)</func</fun
c
48. <func<func {</func</func
49. <func<func db.Set().AddRange(entities);</func</func
50. <func<func }</func</func
51. <func<func</func</func
52. <func<func public void Remove(TEntity entity)</func</func
53. <func<func {</func</func
54. <func<func db.Set().Remove(entity);</func</func
55. <func<func }</func</func
56. <func<func</func</func
57. <func<func public void RemoveRange(IEnumerable entities)</func</
func
58. <func<func {</func</func
59. <func<func db.Set().RemoveRange(entities);</func</func
60. <func<func }</func</func
61. <func<func</func</func
62. <func<func public void Remove(object Id)</func</func
63. <func<func {</func</func
64. <func<func TEntity entity = db.Set().Find(Id);</func</func
65. <func<func this.Remove(entity);</func</func
66. <func<func }</func</func
67. <func<func</func</func
68. <func<func public void Update(TEntity entity)</func</func
69. <func<func {</func</func
70. <func<func db.Entry(entity).State = EntityState.Modified;</func<
/func
71. <func<func }</func</func
72. <func<func}</func</func

2. Non-Generic Repository Pattern (Specific Repository)


A non-generic repository implementation is used to define all database operation
related to an entity within a separate class. For example, if you have two entities
Category and Product, each entity will have its own implementation repository.
1. public interface IProductRepository
2. {
3. IEnumerable GetAll();
4. IEnumerable Find(Expression<func> predicate);</func
5. <func Product Get(int Id);</func
6. <func</func
7. <func void Add(Product entity);</func
8. <func void AddRange(IEnumerable entities);</func
9. <func</func
10. <func void Update(Product entity);</func
11. <func</func
12. <func void Remove(int Id);</func
13. <func void Remove(Product entity);</func
14. <func void RemoveRange(IEnumerable entities);</func
15. <func}</func
16. <func</func
17. <func// implementation</func
18. <funcpublic class ProductRepository</func
19. <func{</func
20. <func protected readonly DbContext db;</func
21. <func</func
22. <func public Repository(DbContext _db)</func
23. <func {</func
24. <func db = _db;</func
25. <func }</func
26. <func</func
27. <func public IEnumerable GetAll()</func
28. <func {</func
29. <func return db.Products.ToList();</func
30. <func }</func
31. <func</func
32. <func public IEnumerable Find(Expression<func> predicate)</func<
/func
33. <func<func {</func</func
34. <func<func return db.Products.Where(predicate);</func</func
35. <func<func }</func</func
36. <func<func</func</func
37. <func<func public Product Get(int Id)</func</func
38. <func<func {</func</func
39. <func<func return db.Products.Find(Id);</func</func
40. <func<func }</func</func
41. <func<func</func</func
42. <func<func public void Add(Product entity)</func</func
43. <func<func {</func</func
44. <func<func db.Products.Add(Product);</func</func
45. <func<func }</func</func
46. <func<func</func</func
47. <func<func public void AddRange(IEnumerable entities)</func</fun
c
48. <func<func {</func</func
49. <func<func db.Products.AddRange(entities);</func</func
50. <func<func }</func</func
51. <func<func</func</func
52. <func<func public void Remove(Product entity)</func</func
53. <func<func {</func</func
54. <func<func db.Products.Remove(entity);</func</func
55. <func<func }</func</func
56. <func<func</func</func
57. <func<func public void RemoveRange(IEnumerable entities)</func</
func
58. <func<func {</func</func
59. <func<func db.Products.RemoveRange(entities);</func</func
60. <func<func }</func</func
61. <func<func</func</func
62. <func<func public void Remove(object Id)</func</func
63. <func<func {</func</func
64. <func<func Product entity = db.Products.Find(Id);</func</func
65. <func<func this.Remove(entity);</func</func
66. <func<func }</func</func
67. <func<func</func</func
68. <func<func public void Update(Product entity)</func</func
69. <func<func {</func</func
70. <func<func db.Entry(entity).State = EntityState.Modified;</func<
/func
71. <func<func }</func</func
72. <func<func}</func</func

Recommended Repository Pattern


Implementation
If you will use one of the above implementation, generic you can not use for specific
operation on an entity and in case of non-generic implementation, you have to write code
for common CRUD operations for each entity. So better way is, just create a generic
repository for commonly used CRUD operation and for specific one create a non-generic
repository and inherit form generic repository. The example code is given below:
1. public interface IProductRepository : IRepository
2. {
3. IEnumerable GetProductsByCategory(int id);
4. }
5.
6. public class ProductRepository : Repository, IProductRepository
7. {
8. public DatabaseContext context
9. {
10. get
11. {
12. return db as DatabaseContext;
13. }
14. }
15.
16. public ProductRepository(DatabaseContext _db) : base(_db)
17. {
18.
19. }
20.
21. public IEnumerable GetProductsByCategory(int id)
22. {
23. return context.Products.Where(p => p.CategoryId == id).ToList();
24. }
25. }

Unit of work Pattern


The unit of pattern implementation manage in-memory database CRUD operations on
entities as one transaction. So, if one of the operation is failing then entire db operations
will be rollback.

1.
2. public interface IUnitOfWork : IDisposable
3. {
4. ICategoryRepository Categories { get; }
5. IProductRepository Products { get; }
6.
7. int SaveChanges();
8. }
9.
10. public class UnitOfWork : IUnitOfWork
11. {
12. private readonly DatabaseContext db;
13.
14. public UnitOfWork()
15. {
16. db = new DatabaseContext();
17. }
18.
19. private ICategoryRepository _Categories;
20. public ICategoryRepository Categories
21. {
22. get
23. {
24. if (this._Categories == null)
25. {
26. this._Categories = new CategoryRepository(db);
27. }
28. return this._Categories;
29. }
30. }
31.
32. private IProductRepository _Products;
33. public IProductRepository Products
34. {
35. get
36. {
37. if (this._Products == null)
38. {
39. this._Products = new ProductRepository(db);
40. }
41. return this._Products;
42. }
43. }
44.
45. public int SaveChanges()
46. {
47. return db.SaveChanges();
48. }
49.
50. public void Dispose()
51. {
52. db.Dispose();
53. }
54. }

Entity Framework and Repository and Unit Of


Work Patterns
Entity Framework is based on the repository and unit of work patterns to perform CRUD
operations on an entity.

The DbSet class is based on the repository design pattern which provides us a set of
method to perform CRUD operations on an entity. The DbContext class is based on unit
of work pattern which includes all the DbSet entities. The DbContext class manages in-
memory database operations on these entities and later saves all these updates as one
transaction into database.

Advantages of Repository and Unit Of Work


Design Patterns
1. Abstract Data Access Layer and Business Access Layer from the Application.
2. Manage in-memory database operations and later saves in-memory updates as one
transaction into database.
3. Facilitates to make the layers loosely-coupled using dependency injection.
4. Facilitates to follow unit testing or test-driven development (TDD).

Advanced

Understanding Controllers and


Actions in MVC Razor
Asp.net MVC Controllers are responsible for controlling the flow of the application
execution. When you make a request (means request a page) to MVC applications , a
controller is responsible for returning the response to that request. A controller can have
one or more actions. A controller action can return different types of action results to a
particular request.

Controller
Basically, the controller Receives input like as form values, query strings values etc. from
users via the View and perform required operations on the user's inputs with the help of
Model and passing the results back to the View. Actually, controllers are classes that have
methods or action results and these actions results are called by the routing system to
process a particular request.

Creating a Controller
For creating a controller, do right-click on the Controller folder in your mvc application
and select the menu option Add, Controller. After selection the Add Controller dialog is
being displayed as shown in fig. Now enter your controller name before Controller word.
In this way you have successfully created your controller as shown in fig.
Controller Actions and Helper Methods
Controller actions are methods defined in the controller class and responsible to perform
required operations on the user's inputs like as form values, query strings values etc. with
the help of Model and passing the results back to the View. Asp.net MVC has the following
Built-in ActionResults Type and Helper methods :

1. ViewResult
Returns a ViewResult which renders the specified or default view by using controller
View() helper method.

2. PartialViewResult
Returns a PartialViewResult which renders the specified or default partial view (means
a view without its layout) by using controller PartialView() helper method.

3. RedirectResult
Returns a RedirectResult which Issues an HTTP 301 or 302 redirection to a specific
URL by using controller Redirect() helper method.

4. RedirectToRouteResult
Returns a RedirectToRouteResult which Issues an HTTP 301 or 302 redirection to an
action method or specific route entry by using controller RedirectToAction(),
RedirectToActionPermanent(), RedirectToRoute(), RedirectToRoutePermanent()
helper methods.

5. ContentResult
Returns a ContentResult which renders raw text like as "Hello, DotNet Tricks!" by
using controller Content() helper method.

6. JsonResult
Returns a JsonResult which serializes an object in JSON format ( like as "{ "Message":
Hello, World! }") and renders it by using controller Json() helper method.

7. JavaScriptResult
Returns a JavaScriptResult which renders a snippet of JavaScript code like as "function
hello() { alert(Hello, World!); }" by using controller JavaScript() helper method. This is
used only in AJAX scenarios.

8. FileResult
Returns a FileResult which renders the contents of a file like as PDF, DOC, Excel etc.
by using controller File() helper method.

9. EmptyResult
Returns no result returned by an action. This has no controller helper method.

10. HttpNotFoundResult
Returns an HttpNotFoundResult which renders a 404 HTTP Status Code response by
using controller HttpNotFound() helper method.
11. HttpUnauthorizedResult
Returns an HttpUnauthorizedResult which renders a 401 HTTP Status Code(means
"not authorized") response. This has no controller helper method. This is used for
authentication (forms authentication or Windows authentication) to ask the user to
log in.

12. HttpStatusCodeResult
Returns an HttpStatusCodeResult which renders a specified HTTP code response. This
has no controller helper method.

Source Code Print


30 Nov 2012

13 Sep 2018

Intermediate

185K

Server side validations are required for ensuring that the received data is correct and valid.
If the received data is valid then we do the further processing with the data. Server side
validations are very important before playing with sensitive information of a user.
Server-side validation must be done whether we validate the received data on the client
side. User could disable script in his browser or do something else to bypass client-side
validation. In this case server-side validation must required to protect our data from dirty
input.

Server-side model validation technique


In MVC Razor, we can validate a model server side by below two ways:
1. Explicit Model Validation
2. Model Validation with Data Annotations

Explicit Model Validation


Suppose, you want to validate the registration process of a user for which the Registration
model and view are defined as below:
RegistrationModel.cs
1. public class RegistrationModel
2. {
3. public string UserName { get; set; }
4. public string Password { get; set; }
5. public string ConfirmPassword { get; set; }
6. public Country Country { get; set; }
7. public City City { get; set; }
8. public string Address { get; set; }
9. public string MobileNo { get; set; }
10. public bool TermsAccepted { get; set; }
11. }
12.
13. public class Country
14. {
15. public int? ID { get; set; }
16. public string Name { get; set; }
17. }
18.
19. public class City
20. {
21. public int? ID { get; set; }
22. public string Name { get; set; }
23. public int? Country { get; set; }
24. }

ExplicitServer.cshtml
1. @model Mvc4_Client_ServerSideValidation.Models.RegistrationModel
2. @{
3. ViewBag.Title = "Explicit Server Side Validation";
4. }
5. <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
6. <script type="text/jscript">
7. $(function () {
8. $('#Country_ID').change(function () {
9. var id = $("#Country_ID :selected").val();
10. if (id != "") {
11. $.ajax({
12. type: "GET",
13. contentType: "application/json; charset=utf-8",
14. url: '@Url.Action("CityList", "Home")',
15. data: { "mCountry": id },
16. dataType: "json",
17. success: function (data) {
18. var items = "";
19. $.each(data, function (i, city) {
20. items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
21. });
22. $('#City_ID').html(items);
23. },
24. error: function (result) {
25. alert('Service call failed: ' + result.status + ' Type :' + result.statusText);
26. }
27. });
28. }
29. else
30. {
31. var items = '<option value="">Select</option>';
32. $('#City_ID').html(items);
33. } });
34. });
35. </script>
36. <h2>Explicit Server Side Validation</h2> @using (Html.BeginForm())
37. {
38. <fieldset>
39. <ol>
40. <li>
41. @Html.LabelFor(m => m.UserName)
42. @Html.TextBoxFor(m => m.UserName, new { maxlength = 50 })
43. @Html.ValidationMessageFor(m => m.UserName)
44. </li>
45. <li>
46. @Html.LabelFor(m => m.Password)
47. @Html.PasswordFor(m => m.Password, new { maxlength = 50, value = ViewBag.Selpwd })
48. @Html.ValidationMessageFor(m => m.Password)
49. </li>
50. <li>
51. @Html.LabelFor(m => m.ConfirmPassword)
52. @Html.PasswordFor(m => m.ConfirmPassword, new { maxlength = 50, value = ViewBag.Se
lconfirmpwd })
53. @Html.ValidationMessageFor(m => m.ConfirmPassword)
54. </li>
55. <li>
56. @Html.LabelFor(m => m.Country)
57. @Html.DropDownListFor(m => m.Country.ID, new SelectList(ViewBag.Country, "ID", "Na
me"), new { style = "width:310px" })
58. @Html.ValidationMessageFor(m => m.Country)
59. </li>
60. <li>
61. @Html.LabelFor(m => m.City)
62. @Html.DropDownListFor(m => m.City.ID, new SelectList(ViewBag.City, "ID", "Name"), n
ew { style = "width:310px" })
63. @Html.ValidationMessageFor(m => m.City)
64. </li>
65. <li>
66. @Html.LabelFor(m => m.Address)
67. @Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
68. @Html.ValidationMessageFor(m => m.Address)
69. </li>
70. <li>
71. @Html.LabelFor(m => m.MobileNo)
72. @Html.TextBoxFor(m => m.MobileNo, new { maxlength = 10 })
73. @Html.ValidationMessageFor(m => m.MobileNo)
74. </li>
75. <li>
76. @Html.CheckBoxFor(m => m.TermsAccepted) I accept the terms & conditions
77. @Html.ValidationMessageFor(m => m.TermsAccepted)
78. </li>
79. </ol>
80. <input type="submit" value="Submit" />
81. </fieldset>
82. }
Now let's see how we validate the model explicitly?. To validate a model explicitly we need
to validate received data with in the action method like as:
1. [HttpPost]
2. public ActionResult ExplicitServer(RegistrationModel mRegister)
3. {
4. //Write custom logic to validate RegistrationModel
5. if (string.IsNullOrEmpty(mRegister.UserName))
6. {
7. ModelState.AddModelError("UserName", "Please enter your name");
8. }
9. if (!string.IsNullOrEmpty(mRegister.UserName))
10. {
11. Regex emailRegex = new Regex(".+@.+\\..+");
12. if (!emailRegex.IsMatch(mRegister.UserName))
13. ModelState.AddModelError("UserName", "Please enter correct email address");
14. }
15. if (string.IsNullOrEmpty(mRegister.Password))
16. {
17. ModelState.AddModelError("Password", "Please enter password");
18. }
19. if (string.IsNullOrEmpty(mRegister.ConfirmPassword))
20. {
21. ModelState.AddModelError("ConfirmPassword", "Please enter confirm password");
22. }
23. if (string.IsNullOrEmpty(mRegister.ConfirmPassword) && string.IsNullOrEmpty(mRegis
ter.ConfirmPassword))
24. {
25. if (mRegister.ConfirmPassword != mRegister.Password)
26. ModelState.AddModelError("ConfirmPassword", "Confirm password doesn't match");
27. }
28. if (mRegister.Country.ID == null || mRegister.Country.ID == 0)
29. {
30. ModelState.AddModelError("Country", "Please select Country");
31. }
32. if (mRegister.City.ID == null || mRegister.City.ID == 0)
33. {
34. ModelState.AddModelError("City", "Please select City");
35. }
36. if (string.IsNullOrEmpty(mRegister.Address))
37. {
38. ModelState.AddModelError("Address", "Please enter your address");
39. }
40. if (string.IsNullOrEmpty(mRegister.MobileNo))
41. {
42. ModelState.AddModelError("MobileNo", "Please enter your mobile no");
43. }
44. if (!mRegister.TermsAccepted)
45. {
46. ModelState.AddModelError("TermsAccepted", "You must accept the terms");
47. }
48. if (ModelState.IsValid)
49. {
50. return View("Completed");
51. }
52. else
53. {
54. ViewBag.Selpwd = mRegister.Password;
55. ViewBag.Selconfirmpwd = mRegister.ConfirmPassword;
56. BindCountry();
57.
58. if (mRegister.Country != null)
59. BindCity(mRegister.Country.ID);
60. else BindCity(null);
61.
62. return View();
63. }
64. }

How it works...
Afer running the project and navigating to ExplicitServer page you will get the below page.
When you press the submit button on this page then it will post the data to the server
and the code written with in ExplicitServer action will validate the input data. If input data
is not valid then add error to model state by using method AddModelError() as shown
above.
When all the validation will be passed then ModelState.IsValid returns true and you will
be shown Completed view as shown in fig.

Model Validation with Data Annotations


The another and best way to validate a model by using Data Annotations. Data
Annotations was introduced with .Net 3.5 SP1. It has a set of attributes and classes defined
in the System.ComponentModel.DataAnnotations assembly. Data Annotations allow us to
decorate model classes with metadata. This metadata describes a set of rules that are
used to validate a property. For more help refer the article MVC Data Annotation.
In RegistrationModel.cs, I have defined one more model class RegistrationMetaModel by
using data annotation and for which the view is defined as below:

RegistrationModel.cs
1. public class RegistrationMetaModel
2. {
3. [Required(ErrorMessage = "Please Enter Email Address")]
4. [Display(Name = "UserName (Email Address)")]
5. [RegularExpression(".+@.+\\..+", ErrorMessage = "Please Enter Correct Email Addres
s")]
6. public string UserName { get; set; }
7.
8. [Required(ErrorMessage = "Please Enter Password")]
9. [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", M
inimumLength = 6)]
10. [DataType(DataType.Password)]
11. [Display(Name = "Password")]
12. public string Password { get; set; }
13.
14. [Required(ErrorMessage = "Please Enter Confirm Password")]
15. [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", M
inimumLength = 6)]
16. [DataType(DataType.Password)]
17. [Display(Name = "Confirm password")]
18. [Compare("Password", ErrorMessage = "The password and confirmation password do not
match.")]
19. public string ConfirmPassword { get; set; }
20.
21. [Display(Name = "Country")] [ValidCountryAttribute(ErrorMessage = "Please Select C
ountry")]
22. public Country Country { get; set; }
23.
24. [Display(Name = "City")]
25. [ValidCityAttribute(ErrorMessage = "Please Select City")]
26. public City City { get; set; }
27.
28. [Required(ErrorMessage = "Please Enter Address")]
29. [Display(Name = "Address")]
30. [MaxLength(200)]
31. public string Address { get; set; }
32.
33. [Required(ErrorMessage = "Please Enter Mobile No")]
34. [Display(Name = "Mobile")]
35. [StringLength(10, ErrorMessage = "The Mobile must contains 10 characters", Minimum
Length = 10)]
36. public string MobileNo { get; set; }
37.
38. [MustBeTrue(ErrorMessage = "Please Accept the Terms & Conditions")]
39. public bool TermsAccepted { get; set; }
40. }
41.
42. public class MustBeTrueAttribute : ValidationAttribute
43. {
44. public override bool IsValid(object value)
45. {
46. return value is bool && (bool)value;
47. }
48. }
49. public class ValidCountryAttribute : ValidationAttribute
50. {
51. public override bool IsValid(object value)
52. {
53. if (((Country)value).ID == null || ((Country)value).ID == 0)
54. return false;
55. else
56. return true;
57. }
58. }
59. public class ValidCityAttribute : ValidationAttribute
60. {
61. public override bool IsValid(object value)
62. {
63. if (((City)value).ID == null || ((City)value).ID == 0)
64. return false;
65. else
66. return true;
67. }
68. }

ServerMeta.cshtml
1. @model Mvc4_Model_ServerSideValidation.Models.RegistrationMetaModel
2. @{
3. ViewBag.Title = "Server Side Validation by Specifying Validation Rules Using Metad
ata";
4. }
5. <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
6. <script type="text/jscript">
7. $(function ()
8. {
9. $('#Country_ID').change(function ()
10. {
11. var id = $("#Country_ID :selected").val();
12. if (id != "")
13. {
14. $.ajax({
15. type: "GET",
16. contentType: "application/json; charset=utf-8",
17. url: '@Url.Action("CityList", "Home")',
18. data: { "mCountry": id },
19. dataType: "json",
20. beforeSend: function () {
21. },
22. success: function (data) {
23. var items = "";
24. $.each(data, function (i, city) {
25. items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
26. });
27. $('#City_ID').html(items);
28. },
29. error: function (result) {
30. alert('Service call failed: ' + result.status + ' Type :' + result.statusText);
31. }
32. });
33. }
34. else {
35. var items = '<option value="">Select</option>';
36. $('#City_ID').html(items);
37. }
38. });
39. });
40. </script>
41. <h2>Server Side Validation by Specifying Validation Rules Using Metadata</h2>
42. @using (Html.BeginForm())
43. {
44. <fieldset>
45. <ol>
46. <li>
47. @Html.LabelFor(m => m.UserName)
48. @Html.TextBoxFor(m => m.UserName, new { maxlength = 50 })
49. @Html.ValidationMessageFor(m => m.UserName)
50. </li>
51. <li>
52. @Html.LabelFor(m => m.Password)
53. @Html.PasswordFor(m => m.Password, new { maxlength = 50, value = ViewBag.Selpwd })
54. @Html.ValidationMessageFor(m => m.Password)
55. </li>
56. <li>
57. @Html.LabelFor(m => m.ConfirmPassword)
58. @Html.PasswordFor(m => m.ConfirmPassword, new { maxlength = 50, value = ViewBag.Se
lconfirmpwd })
59. @Html.ValidationMessageFor(m => m.ConfirmPassword)
60. </li>
61. <li>
62. @Html.LabelFor(m => m.Country)
63. @Html.DropDownListFor(m => m.Country.ID, new SelectList(ViewBag.Country, "ID", "Na
me", ViewBag.SelCountry), new { style = "width:310px" })
64. @Html.ValidationMessageFor(m => m.Country)
65. </li>
66. <li>
67. @Html.LabelFor(m => m.City)
68. @Html.DropDownListFor(m => m.City.ID, new SelectList(ViewBag.City, "ID", "Name", V
iewBag.SelCity), new { style = "width:310px" })
69. @Html.ValidationMessageFor(m => m.City)
70. </li>
71. <li>
72. @Html.LabelFor(m => m.Address)
73. @Html.TextAreaFor(m => m.Address, new { maxlength =200 })
74. @Html.ValidationMessageFor(m => m.Address)
75. </li>
76. <li>
77. @Html.LabelFor(m => m.MobileNo)
78. @Html.TextBoxFor(m => m.MobileNo ,new { maxlength = 10 })
79. @Html.ValidationMessageFor(m => m.MobileNo)
80. </li>
81. <li>
82. @Html.CheckBoxFor(m => m.TermsAccepted) I accept the terms & conditions
83. @Html.ValidationMessageFor(m => m.TermsAccepted)
84. </li>
85. </ol>
86. <input type="submit" value="Submit" />
87. </fieldset>
88. }
Now let's see how we validate the model using data annotation?. To validate a model
explicitly we need to validate received data with in the action method by checking
ModelState.IsValid property. If it is false then error message will be shown automatically
against each propety of model as shown below in fig.
1. [HttpPost]
2. public ActionResult ServerMeta(RegistrationMetaModel mRegister)
3. {
4. if (ModelState.IsValid)
5. {
6. return View("Completed");
7. }
8. else
9. {
10. ViewBag.Selpwd = mRegister.Password;
11. ViewBag.Selconfirmpwd = mRegister.ConfirmPassword;
12. BindCountry();
13.
14. if (mRegister.Country != null)
15. BindCity(mRegister.Country.ID);
16. else
17. BindCity(null);
18. return View();
19. }
20. }

How it works...
After running the project and navigating to Data Annotation-Server-Side page you will
get the below page. When you press the submit button on this page then it will post the
data to the server and the code written with in ServerMeta action will validate the input
data by checking ModelState.IsValid property. If input data is not valid then
ModelState.IsValid will return false and shown error as shown below.
When all the validation will be passed then ModelState.IsValid returns true and you will
be shown Completed view as shown in fig.

Basically, Routing is a pattern matching system that monitor the incoming request and
figure out what to do with that request. At runtime, Routing engine use the Route table
for matching the incoming request's URL pattern against the URL patterns defined in the
Route table. You can register one or more URL patterns to the Route table at
Application_Start event. MVC5 also supports attribute routing, to know more
refer Attribute Routing in ASP.NET MVC.

How to define route...


1. public static void RegisterRoutes(RouteCollection routes)
2. {
3. routes.MapRoute(
4. "Default", // Route name
5. "{controller}/{action}/{id}", // Route Pattern
6. new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Defau
lt values for above defined parameters
7. );
8. }
9.
10. protected void Application_Start()
11. {
12. RegisterRoutes(RouteTable.Routes);
13. //To:DO
14. }
When the routing engine finds a match in the route table for the incoming request's URL,
it forwards the request to the appropriate controller and action. If there is no match in the
route table for the incoming request's URL, it returns a 404 HTTP status code.

Note
Always remember route name should be unique across the entire application. Route
name can’t be duplicate.

How it works...
In above example we have defined the Route Pattern {controller}/{action}/{id} and also
provide the default values for controller,action and id parameters. Default values means
if you will not provide the values for controller or action or id defined in the pattern then
these values will be serve by the routing system.
Suppose your webapplication is running on www.example.com then the url pattren for
you application will be www.example.com/{controller}/{action}/{id}. Hence you need to
provide the controller name followed by action name and id if it is required. If you will not
provide any of the value then default values of these parameters will be provided by the
routing system. Here is a list of URLs that match and don't match this route pattern.
Matching URLs

Request URL

Parameters

http://example.com/

controller=Home, action=Index, id=none, Since default value of controller and action are Home
and Index respectively.

http://example.com/Admin
controller=Admin, action=Index, id=none, Since default value of action is Index

http://example.com/Admin/Product

controller=Admin, action=Product, id=none

http://example.com/Admin/Product/1

controller=Admin, action=Product, id=1

http://example.com/Admin/Product/SubAdmin/1

No Match Found

http://example.com/Admin/Product/SubAdmin/Add/1

No Match Found

Difference between Routing and URL Rewriting


Many developers compare routing to URL rewriting that is wrong. Since both the
approaches are very much different. Moreover, both the approaches can be used to make
SEO friendly URLs. Below is the main difference between these two approaches.
1. URL rewriting is focused on mapping one URL (new url) to another URL (old url) while
routing is focused on mapping a URL to a resource.
2. Actually, URL rewriting rewrites your old url to new one while routing never rewrite
your old url to new one but it map to the original route.
In previous article, I have described the Routing and how to create route in your
application. Now the time is how to control the behavior of a route. Basically route
constraints is way to put some validation around the defined route.

Creating Route Constraints


Suppose we have defined the following route in our application and you want to restrict
the incoming request url with numeric id only.Now let's see how to do it with the help of
regular expression.
1. routes.MapRoute(
2. "Default", // Route name
3. "{controller}/{action}/{id}", // Route Pattern
4. new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Defau
lt values for parameters
5. );
Restrict to numeric id only
1. routes.MapRoute(
2. "Default", // Route name
3. "{controller}/{action}/{id}", // Route Pattern
4. new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Defa
ult values for parameters
5. new { id = @"\d+" } //Restriction for id
6. );
Now for this route, routing engine will consider only those URLs which have only numeric
id like as http://example.com/Admin/Product/1 else it will considers that url is not
matched with this route.

Creating Route Constraint to a Set of Specific Values


Suppose you want to restrict the user for those URLs that have controller name with H
prefix and action name should be only Index or Contact. Now let's see how to do it with
the help of regular expression.
1. routes.MapRoute(
2. "Default", // Route name
3. "{controller}/{action}/{id}", // Route Pattern
4. new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Defa
ult values for parameters
5. new { controller = "^H.*", action = "^Index$|^Contact$" } //Restriction for contro
ller and action
6. );
Now for this route, routing engine will consider only those URLs which have controller
name with H prefix and action name should be only Index or Contact like as
http://example.com/Home/Index, http://example.com/Home/Contact and
http://example.com,http://example.com/Home else it will considers that url is not
matched with this route.
You are little bit confused why it will consider the
http://example.com,http://example.com/Home URLs ?. It will also consider both these
since route constraints is checked after the provided default values for controller and
action. In above route default values for controller and action are Home and Index so
these two URLs will also be matched. Like this you can restrict the user according to your
need.
The Model-View-Controller (MVC) pattern was introduced in the 1970s. It is a software
design pattern that splits an application into three main aspects : Model, View and
Controller. Moreover, MVC pattern forces a separation of concerns within an
application for example, separating data access logic and business logic from the UI.

Model - The "M" in "MVC"


The Model represents a set of classes that describes the business logic and data. It also
defines business rules for how the data can be changed and manipulated.
Moreover, models in Asp.Net MVC, handles the Data Access Layer by using ORM tools
like Entity Framework or NHibernate etc. By default, models are stored in the Models
folder of the project.

The Model can be broken down into several different


layers as given below:

1. Objects or ViewModel Layer


This layer contains simple objects or complex objects which are used to specify
strongly-typed view. These objects are used to pass data from controller to strongly-
typed view and vice versa. The classes for these objects can have specific validation
rules which are defined by using data annotations. Typically, these classes have those
properties which you want to display on corresponding view/page.

2. Data Access Layer


This layer provides objects to access and manipulate the database of your application.
Typically, this layer is made by using ORM tools like Entity Framework or NHibernate
etc.

3. Business Layer
This layer helps you to implement your business logic and validations for your
application. This layer make use of Data Access Layer for persisting data into
database. Also, this layer is directly invoked by the Controller to do processing on
input data and sent back to view.

View - The "V" in "MVC"


The View is responsible for transforming a model or models into UI. The Model is
responsible for providing all the required business logic and validation to the view. The
view is only responsible for displaying the data, that is received from the controller as the
result.
Moreover, views in Asp.Net MVC, handles the UI presentation of data as the result of a
request received by a controller. By default, views are stored in the Views folder of the
project.
Controller - The "C" in "MVC"
The Controller is responsible for controlling the application logic and acts as the
coordinator between the View and the Model. The Controller receive input from users via
the View, then process the user's data with the help of Model and passing the results back
to the View.
Moreover, controllers in Asp.Net MVC, respond to HTTP requests and determine the
action to take based upon the content of the incoming request. By default, controllers are
stored in the Controllers folder of the project.
 rendering layouts in Asp.Net MVC
 How to get textboxes values in MVC4 created by jQuery
 Changing browser URL with jQuery mobile and Asp.Net MVC
 Understanding ASP.NET MVC Filters and Attributes
 Persisting Data with TempData
 Understanding HTML Helpers in ASP.NET MVC
 Understanding AJAX Helpers in ASP.NET MVC
 Understanding ASP.NET MVC Scaffolding
 Layouts, RenderBody, RenderSection and RenderPage in ASP.NET MVC
 Understanding Attribute Routing in ASP.NET MVC
 Understanding Internationalization in ASP.NET MVC
Advanced

MVC Areas with example

Shailendra Chauhan Print


01 Jan 2013

26 Sep 2016

Intermediate

166K
Areas was introduced in Asp.net MVC2 which allow us to organize models, views, and
controllers into separate functional sections of the application, such as administration,
billing, customer support, and so on. This is very helpful in a large web application, where
all the controllers, views, and models have a single set of folders and that become difficult
to manage.
Each MVC area has its own folder structure which allow us to keep separate controllers,
views, and models. This also helps the multiple developers to work on the same web
application without interfere to one another.

Registering Area
Before working with area, make sure you have registered your area with in the
Application_Start method in Global.asax as shown below.
1. protected void Application_Start()
2. {
3. //Register all application Areas
4. AreaRegistration.RegisterAllAreas();
5.
6. WebApiConfig.Register(GlobalConfiguration.Configuration);
7. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
8. RouteConfig.RegisterRoutes(RouteTable.Routes);
9. BundleConfig.RegisterBundles(BundleTable.Bundles);
10.
11. }

Note
Always remember the order of registering the Areas must be on top, so that all of the
settings, filters and routes registered for the applications will also apply on the Areas.

Creating Area
To add an area to an MVC application, right-click on the project item with in the Solution
Explorer window and select Add>Area option as shown below.
Now a new prompt will appear, with in give the name of the area like "Department" and
click Add button. Now the new Department Area has been cretaed as shown in below fig.
Now you have seen DepartmentAreaRegistration class has been created and in the
RegisterArea method, a route for the area has been defined as shown below.
1. using System.Web.Mvc;
2. namespace Mvc4Area.Areas.Department
3. {
4. public class DepartmentAreaRegistration : AreaRegistration
5. {
6. public override string AreaName
7. {
8. get
9. {
10. return "Department";
11. }
12. }
13.
14. public override void RegisterArea(AreaRegistrationContext context)
15. {
16. context.MapRoute(
17. "Department_default",
18. "Department/{controller}/{action}/{id}",
19. new { action = "Index", id = UrlParameter.Optional }
20. );
21. }
22. }
23. }

Populating Area
Now you can create controllers, views, and models in the Department area like as below.
How to see view with in Areas
Now, let's see how to view your Index view with the help of Page Inspector as shown
below.
By default, Asp.Net MVC support session state. Session is used to store data values across
requests. Whether you store some data values with in the session or not Asp.Net MVC
must manage the session state for all the controllers in your application that is time
consuming. Since, session is stored on server side and consumes server memory, hence it
also affect your application performance.

Session Less Controller


If some of the controllers of your Asp.Net MVC application are not using session state
features, you can disable session for those controller and can gain slight performance
improvement of your application. You can simplify session state for your application by
using available options for session state.
In Asp.Net MVC4, SessionState attribute provides you more control over the behavior of
session-state by specifying the value of SessionStateBehavior enumeration as shown
below:
SessionStateBehavior Enumeration's Value

Value

Description

Default

The default Asp.Net behavior is used to determine the session state behavior.

Disabled

Session state is disabled entirely.

ReadOnly

Read-only session state behavior is enabled.

Required

Full read-write session state behavior is enabled.

In Asp.Net MVC, TempData use session state for storing the data values across requests.
Hence, when you will disabled the session state for the controller, it will throw the
exception as shown below:
There are different ways for rendering a partial view in MVC Razor. Many developers got
confused whether to use RenderPartial or RenderAction or Partial or Action helper
methods for rendering a partial view. In this article, I would like to expose the difference
among Html.RenderPartial, Html.RenderAction, Html.Partial & Html.Action.

Html.RenderPartial
1. This method result will be directly written to the HTTP response stream means it used
the same TextWriter object as used in the current webpage/template.
2. This method returns void.
3. Simple to use and no need to create any action.
4. RenderPartial method is useful when the displaying data in the partial view is already
in the corresponding view model.For example : In a blog to show comments of an
article, we would like to use RenderPartial method since an article information with
comments are already populated in the view model.
1. @{Html.RenderPartial("_Comments");}
5. This method is faster than Partial method since its result is directly written to the
response stream which makes it fast.

Html.RenderAction
1. This method result will be directly written to the HTTP response stream means it used
the same TextWriter object as used in the current webpage/template.
2. For this method, we need to create a child action for the rendering the partial view.
3. RenderAction method is useful when the displaying data in the partial view is
independent from corresponding view model.For example : In a blog to show
category list on each and every page, we would like to use RenderAction method
since the list of category is populated by the different model.
1. @{Html.RenderAction("Category","Home");}
4. This method is the best choice when you want to cache a partial view.
5. This method is faster than Action method since its result is directly written to the
HTTP response stream which makes it fast.
Html.Partial
1. Renders the partial view as an HTML-encoded string.
2. This method result can be stored in a variable, since it returns string type value.
3. Simple to use and no need to create any action.
4. Like RenderPartial method, Partial method is also useful when the displaying data in
the partial view is already in the corresponding view model. For example: In a blog to
show comments of an article, you can use Partial method since an article information
with comments are already populated in the view model.
1. @Html.Partial("_Comments")

Html.Action
1. Renders the partial view as an HtmlString .
2. For this method, we need to create a child action for the rendering the partial view.
3. This method result can be stored in a variable, since it returns string type value.
4. Action method is useful when the displaying data in the partial view is independent
from corresponding view model.For example : In a blog to show category list on
each and every page, we would like to use Action method since the list of category
is populated by the different model.
1. @{Html.Action("Category","Home");}
5. This method is also the best choice when you want to cache a partial view.
There are many ways for returning or rendering a view in ASP.NET MVC. Many developers
got confused when to use View(), RedirectToAction(), Redirect() and RedirectToRoute()
methods. In this article, I would like to explain the difference among "View()" and
"RedirectToAction()", "Redirect()" and "RedirectToRoute()" methods.

The View() Method


This method is used to generates the HTML markup to be displayed for the specified view
and sends it to the browser. This acts just like as Server.Transfer() method in ASP.NET
WebForm.
1. public ActionResult Index()
2. {
3. return View();
4. }
5.
6. [HttpPost]
7. public ActionResult Index(string Name)
8. {
9. ViewBag.Message = "Hi, Dot Net Tricks";
10. //Like Server.Transfer() in Asp.Net WebForm
11. return View("MyIndex");
12. }
13.
14. public ActionResult MyIndex()
15. {
16. ViewBag.Msg = ViewBag.Message; // Assigned value : "Hi, Dot Net Tricks"
17. return View("MyIndex");
18. }
What happens if we call the action method directly like return MyIndex(). It is simply a
method call which returns a rendered view that is specified in MyIndex() action method.
1. public ActionResult Index()
2. {
3. return View();
4. }
5.
6. [HttpPost]
7. public ActionResult Index(string Name)
8. {
9. ViewBag.Message = "Hi, Dot Net Tricks";
10. //Like Server.Transfer() in Asp.Net WebForm
11. return MyIndex();
12. }
13.
14. public ActionResult MyIndex()
15. {
16. ViewBag.Msg = ViewBag.Message; // Assigned value : "Hi, Dot Net Tricks"
17. return View("MyIndex");
18. }

The RedirectToAction() Method


This method is used to redirect to specified action instead of rendering the HTML. In this
case, browser receives the redirect notification and make a new request for the specified
action. This acts just like as Response.Redirect() in ASP.NET WebForm.
Moreover, RedirectToAction construct a redirect url to a specific action/controller in your
application and use the route table to generate the correct URL. RedirectToAction cause
the browser to receive a 302 redirect within your application and gives you an easier way
to work with your route table.
1. public ActionResult Index()
2. {
3. return View();
4. }
5.
6. [HttpPost]
7. public ActionResult Index(string Name)
8. {
9. ViewBag.Message = "Hi, Dot Net Tricks";
10. //Like Response.Redirect() in Asp.Net WebForm
11. return RedirectToAction("MyIndex");
12. }
13.
14. public ActionResult MyIndex()
15. {
16. ViewBag.Msg = ViewBag.Message; // Assigned value : Null
17. return View("MyIndex");
18. }

The Redirect() Method


This method is used to redirect to specified URL instead of rendering HTML. In this case,
browser receives the redirect notification and make a new request for the specified URL.
This also acts like as Response.Redirect() in Asp.Net WebForm. In this case, you have to
specify the full URL to redirect.
Moreover, Redirect also cause the browser to receive a 302 redirect within your
application, but you have to construct the URLs yourself.
1. public ActionResult Index()
2. {
3. return View();
4. }
5.
6. [HttpPost]
7. public ActionResult Index(string Name)
8. {
9. ViewBag.Message = "Hi, Dot Net Tricks";
10. //Like Response.Redirect() in Asp.Net WebForm
11. return Redirect("Home/MyIndex");
12. }
13.
14. public ActionResult MyIndex()
15. {
16. ViewBag.Msg = ViewBag.Message; // Assigned value : Null
17. return View("MyIndex");
18. }

The RedirectToRoute() Method


This method looks up the specifies route into the Route table that is is defined in
global.asax and then redirect to that controller/action defined in that route. This also make
a new request like RedirectToAction().

Definining Route
1. public static void RegisterRoutes(RouteCollection routes)
2. {
3. routes.MapRoute(
4. "MyRoute", // Route name
5. "Account/", // URL
6. new { controller = "Account", action = "Login"} // Parameter defaults
7. );
8.
9. routes.MapRoute(
10. "Default", // Route name
11. "{controller}/{action}/{id}", // URL with parameters
12. new { controller = "Home", action = "MyIndex", id = UrlParameter.Optional } // Par
ameter defaults
13. );
14. }

HomeController
1.
2. public ActionResult Index()
3. {
4. return View();
5. }
6.
7. [HttpPost]
8. public ActionResult Index(string Name)
9. {
10. return RedirectToRoute("MyRoute");
11. }

AccountController
1.
2. public ActionResult Login()
3. {
4. return View();
5. }

Important Note
1. The View() method doesn't make a new requests, it just renders the view without
changing URLs in the browser's address bar.
2. The RedirectToAction() method makes a new requests and URL in the browser's address
bar is updated with the generated URL by MVC.
3. The Redirect() method also makes a new requests and URL in the browser's address bar
is updated, but you have to specify the full URL to redirect
4. Between RedirectToAction() and Redirect() methods, best practice is to use
RedirectToAction() for anything dealing with your application actions/controllers. If you
use Redirect() and provide the URL, you'll need to modify those URLs manually when you
change the route table.
5. RedirectToRoute() redirects to a specific route defined in the Route table.
Sometimes, your required to save Html data in the database. By default Asp.Net MVC
doesn't allow a user to submit html for avoiding Cross Site Scripting attack to your
application. Suppose you have below form and you can submit the Html in description
textarea.

If you do this and try to submit it you will get the error as shown in fig.

However, if you want to do this, you can achieve it by using ValidateInput attribute
and AllowHtmlattribute.

ValidateInput Attribute
This is the simple way to allow the submission of HTML. This attribute can enable or
disable input validation at the controller level or at any action method.

ValidateInput at Controller Level


1.
2. [ValidateInput(false)]
3. public class HomeController : Controller
4. {
5. public ActionResult AddArticle()
6. {
7. return View();
8. }
9.
10. [HttpPost]
11. public ActionResult AddArticle(BlogModel blog)
12. {
13. if (ModelState.IsValid)
14. {
15.
16. }
17. return View();
18. }
19. }
Now, the user can submit Html for this Controller successfully.

ValidateInput at Action Method Level


1.
2. public class HomeController : Controller
3. {
4. public ActionResult AddArticle()
5. {
6. return View();
7. }
8.
9. [ValidateInput(false)]
10. [HttpPost]
11. public ActionResult AddArticle(BlogModel blog)
12. {
13. if (ModelState.IsValid)
14. {
15.
16. }
17. return View();
18. }
19. }
Now, the user can submit Html for this action method successfully.
Limitation of ValidateInput attribute
This attribute also has the issue since this allow the Html input for all the properties and
that is unsafe. Since you have enable Html input for only one-two properties then how to
do this. To allow Html input for a single property, you should use AllowHtml attribute.

AllowHtml Attribute
This is the best way to allow the submission of HTML for a particular property. This
attribute will be added to the property of a model to bypass input validation for that
property only. This explicit declaration is more secure than the ValidateInput attribute.
1. using System.ComponentModel.DataAnnotations;
2. using System.Web.Mvc;
3.
4. public class BlogModel
5. {
6. [Required]
7. [Display(Name = "Title")]
8. public string Title { get; set; }
9.
10. [AllowHtml]
11. [Required]
12. [Display(Name = "Description")]
13. public string Description{ get; set; }
14. }
Make sure, you have removed the ValidateInput attribute from Conroller or Action
method. Now, the user can submit Html only for the Description property successfully.
In Asp.Net MVC, Layouts are like as Master Pages in Asp.Net Web Forms. These helps us
to maintain consistent look and feel across all the views within your Asp.Net MVC
application. Like Master Pages, Layout may contains common CSS, jQuery files across the
multiple Views and one or more placeholders for which Views provide content. For layout
and its components refer this article Layouts, RenderBody, RenderSection and
RenderPage in ASP.NET MVC.
In Asp.Net MVC, at application level we have _ViewStart file with in Views folder for
defining the default Layout page for your Asp.Net MVC application. In this article, I am
going to expose the different ways to apply layout pages for your application. Suppose
we have to render the layouts as shown in the fig. by using various ways.

Method 1 : Control Layouts rendering by using


_ViewStart file in the root directory of the Views
folder
We can change the default rendering of layouts with in _ViewStart file by using the below
code:
1. @{
2. var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Cont
roller"].ToString();
3.
4. string layout = "";
5. if (controller == "Admin")
6. {
7. layout = "~/Views/Shared/_AdminLayout.cshtml";
8. }
9. else
10. {
11. layout = "~/Views/Shared/_Layout.cshtml";
12. }
13.
14. Layout = layout;
15. }
Method 2 : Return Layout from ActionResult
We can also override the default layout rendering by returning the layout from the
ActionResult by using the below code:
1. public ActionResult Index()
2. {
3. RegisterModel model = new RegisterModel();
4. //TO DO:
5. return View("Index", "_AdminLayout", model);
6. }

Method 3 : Define Layout with in each view on


the top
We can also override the default layout rendering by defining the layout on the view by
using the below code:
1. @{
2. Layout = "~/Views/Shared/_AdminLayout.cshtml";
3. }

Method 4 : Adding _ViewStart file in each of the


directories
We can also set the default layout for a particular directory by putting _ViewStart file in
each of the directories with the required Layout information as shown below:
1. @{
2. Layout = "~/Views/Shared/_AdminLayout.cshtml";
3. }
Yesterday, I was trying to get the values of TextBoxes created by jQuery. I was expecting
to get the value of each Textbox created by jQuery by the Id attribute of the TextBox, but
I was getting NULL. I tried to find out the reason behind this reason and finally I got the
solution. Let's understand the ID and Name attribute of Html controls.

1. ID
Id attribute of an input html control is responsible for uniquely identified a control
on the html page. We use Id for getting an input html control's value using jQuery at
client side or for applying some CSS to that control.

2. Name
Name attribute of an input html control is responsible for posting that control values
on server side.
Hence, while creating a Html TextBox or Dropdown list using jQuery also defined the Id
and Name attributes of an Html TextBox or Dropdown list.

Note
When you will not defined the Name attributes of an Html TextBox or Dropdown list
then form will not post the TextBox or Dropdown list values to the server. It means at
controller's action result you will not find the Html TextBox or Dropdown list.
Suppose, you need to select no of customers from drop down list as shown below fig.

Also, Textboxes for entering customers full name are created by jQuery as shown below.
When you will submit the form you will get the Textboxes created by jQuery at controller side as
shown below -

The View
1. <script src="~/Scripts/jquery-1.8.2.js"></script>
2. <script>
3. $(document).ready(function () {
4. $("#ddl").change(function () {
5. var i = $("#ddl :selected").val();
6. var str = "";
7. for (var j = 1; j <= i; j++) {
8. var id = "txtCustomer" + j;
9. //Remember to add name attribute to get values at server side
10. str = str + "<span>Customer " + j + " Full Name: </span><input type='text' id='" +
id + "' name='" + id + "'/><br/>";
11. }
12. $("#content").html(str);
13. });
14. });
15. </script>
16.
17. <br />
18. @using (Html.BeginForm())
19. {
20. <h2>Get TextBoxes Values Created by jQuery</h2>
21.
22. <span>Select No. of Customers </span>
23. <select id="ddl" name="ddl">
24. <option>Select</option>
25. <option>1</option>
26. <option>2</option>
27. <option>3</option>
28. <option>4</option>
29. </select>
30. <br />
31. <div id="content">
32. </div>
33. <br />
34. <div align="center">
35. <input type="submit" id="btnSave" value="Save" />
36. </div>
37. }
You can get the Html TextBox or Dropdown list values created by jQuery by two method
as given below -

Method 1: Get Values Using FormCollection


1. public ActionResult Index()
2. {
3. return View();
4. }
5.
6. [HttpPost]
7. public ActionResult Index(FormCollection form, string ddl)
8. {
9. for (int i = 1; i <= Convert.ToInt32(ddl); i++)
10. {
11. string id = "txtCustomer" + i;
12. string customer = form[id];
13. }
14. return View();
15. }

Method 2: Get Values Using Request.Form


1. public ActionResult Index()
2. {
3. return View();
4. }
5.
6. [HttpPost]
7. public ActionResult Index(string ddl)
8. {
9. for (int i = 1; i <= Convert.ToInt32(ddl); i++)
10. {
11. string id = "txtCustomer" + i;
12. string customer = Request.Form[id];
13. }
14. return View();
15. }
ASP.NET MVC provides a simple way to inject your piece of code or logic either before or
after an action is executed. This is achieved by decorating the controllers or actions with
ASP.NET MVC attributes or custom attributes. An attribute or custom attribute
implements the ASP.NET MVC filters(filter interface) and can contain your piece of code
or logic. You can make your own custom filters or attributes either by implementing
ASP.NET MVC filter interface or by inheriting and overriding methods of ASP.NET MVC
filter attribute class if available.

When to use Filters?


Typically, Filters are used to perform the following common functionalities in your
ASP.NET MVC application.
1. Custom Authentication
2. Custom Authorization(User based or Role based)
3. Error handling or logging
4. User Activity Logging
5. Data Caching
6. Data Compression

Types of Filters
The ASP.NET MVC framework provides five types of filters.
1. Authentication filters (New in ASP.NET MVC5)
2. Authorization filters
3. Action filters
4. Result filters
5. Exception filters
Authentication Filters
This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to
create CustomAuthentication filter. The definition of this interface is given below-
1. public interface IAuthenticationFilter
2. {
3. void OnAuthentication(AuthenticationContext filterContext);
4.
5. void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
6. }
You can create your CustomAuthentication filter attribute by implementing
IAuthenticationFilter as shown below-
1. public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthentication
Filter
2. {
3. public void OnAuthentication(AuthenticationContext filterContext)
4. {
5. //Logic for authenticating a user
6. }
7. //Runs after the OnAuthentication method
8. public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext
)
9. {
10. //TODO: Additional tasks on the request
11. }
12. }

Authorization Filters
The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface.
The definition of this interface is given below-
1. public interface IAuthorizationFilter
2. {
3. void OnAuthorization(AuthorizationContext filterContext);
4. }
The AuthorizeAttribute class provides the following methods to override in the
CustomAuthorize attribute class.
1. public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
2. {
3. protected virtual bool AuthorizeCore(HttpContextBase httpContext);
4. protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContex
t);
5. public virtual void OnAuthorization(AuthorizationContext filterContext);
6. protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpCo
ntext);
7. }
In this way you can make your CustomAuthorize filter attribute either by implementing
IAuthorizationFilter interface or by inheriting and overriding above methods of
AuthorizeAttribute class.
Action Filters
Action filters are executed before or after an action is executed. The IActionFilter interface
is used to create an Action Filter which provides two methods OnActionExecuting and
OnActionExecuted which will be executed before or after an action is executed
respectively.
1. public interface IActionFilter
2. {
3. void OnActionExecuting(ActionExecutingContext filterContext);
4. void OnActionExecuted(ActionExecutedContext filterContext);
5. }

Result Filters
Result filters are executed before or after generating the result for an action. The Action
Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult,
ContentResult, JsonResult, FileResult and EmptyResult which derives from the
ActionResult class. Result filters are called after the Action filters. The IResultFilter interface
is used to create an Result Filter which provides two methods OnResultExecuting and
OnResultExecuted which will be executed before or after generating the result for an
action respectively.
1. public interface IResultFilter
2. {
3. void OnResultExecuted(ResultExecutedContext filterContext);
4. void OnResultExecuting(ResultExecutingContext filterContext);
5. }

Exception Filters
Exception filters are executed when exception occurs during the actions execution or
filters execution. The IExceptionFilter interface is used to create an Exception Filter which
provides OnException method which will be executed when exception occurs during the
actions execution or filters execution.
1. public interface IExceptionFilter
2. {
3. void OnException(ExceptionContext filterContext);
4. }
ASP.NET MVC HandleErrorAttribute filter is an Exception filter which implements
IExceptionFilter. When HandleErrorAttribute filter receives the exception it returns an Error
view located in the Views/Shared folder of your ASP.NET MVC application.

Order of Filter Execution


All ASP.NET MVC filter are executed in an order. The correct order of execution is given
below:
1. Authentication filters
2. Authorization filters
3. Action filters
4. Result filters

Configuring Filters
You can configure your own custom filter into your application at following three levels:

1. Global level

By registering your filter into Application_Start event of Global.asax.cs file with the
help of FilterConfig class.
1. protected void Application_Start()
2. {
3. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
4. }

2. Controller level
By putting your filter on the top of the controller name as shown below-
1. [Authorize(Roles="Admin")]
2. public class AdminController : Controller
3. {
4. //
5. }

3. Action level
By putting your filter on the top of the action name as shown below-
1. public class UserController : Controller
2. {
3. [Authorize(Users="User1,User2")]
4. public ActionResult LinkLogin(string provider)
5. {
6. // TODO:
7. return View();
8. }
9. }
TempData is used to pass data from current request to subsequent request (means
redirecting from one page to another). It’s life is very short and lies only till the target view
is fully loaded. But you can persist data in TempData by calling Keep() method.

TempData with Keep method


If you want to keep value in TempData object after request completion, you need to call Keep
method with in the current action. There are two overloaded Keep methods to retains value
after current request completion.

1. void Keep()
Calling this method with in the current action ensures that all the items in TempData
are not removed at the end of the current request.
1. @model MyProject.Models.EmpModel;
2. @{
3. Layout = "~/Views/Shared/_Layout.cshtml";
4. ViewBag.Title = "About";
5. var tempDataEmployeet = TempData["emp"] as Employee; //need typca
sting
6. TempData.Keep(); // retains all strings values
7. }

2. void Keep(string key)


Calling this method with in the current action ensures that specific item in TempData
is not removed at the end of the current request.
1. @model MyProject.Models.EmpModel;
2. @{
3. Layout = "~/Views/Shared/_Layout.cshtml";
4. ViewBag.Title = "About";
5. var tempDataEmployeet = TempData["emp"] as Employee; //need typca
sting
6. TempData.Keep("emp"); // retains only "emp" string values
7. }

Key point about TempData and TempData.Keep()


1. Items in TempData will only tagged for deletion after they have read.
2. Items in TempData can be untagged by calling TempData.Keep(key).
3. RedirectResult and RedirectToRouteResult always calls TempData.Keep() to retain
items in TempData.
An HTML Helper is just a method that returns a HTML string. The string can represent any
type of content that you want. For example, you can use HTML Helpers to render standard
HTML tags like HTML <input>, <button> and <img> tags etc.
You can also create your own HTML Helpers to render more complex content such as a
menu strip or an HTML table for displaying database data.

Different types of HTML Helpers


There are three types of HTML helpers as given below:

1. Inline Html Helpers

These are create in the same view by using the Razor @helper tag. These helpers can
be reused only on the same view.
1. @helper ListingItems(string[] items)
2. {
3. <ol>
4. @foreach (string item in items)
5. {
6. <li>@item</li>
7. }
8. </ol>
9. }
10.
11. <h3>Programming Languages:</h3>
12.
13. @ListingItems(new string[] { "C", "C++", "C#" })
14.
15. <h3>Book List:</h3>
16.
17. @ListingItems(new string[] { "How to C", "how to C++", "how to
C#" })

2. Built-In Html Helpers


Built-In Html Helpers are extension methods on the HtmlHelper class. The Built-In
Html helpers can be divided into three categories-

1. Standard Html Helpers

These helpers are used to render the most common types of HTML elements like
as HTML text boxes, checkboxes etc. A list of most common standard html
helpers is given below:
HTML Element
Example
TextBox
@Html.TextBox("Textbox1", "val")
Output:
<input id="Textbox1" name="Textbox1" type="text"
value="val" />
TextArea
@Html.TextArea("Textarea1", "val", 5, 15, null)
Output:
<textarea cols="15" id="Textarea1" name="Textarea1"
rows="5">val</textarea>
Password
@Html.Password("Password1", "val")
Output:
<input id="Password1" name="Password1"
type="password" value="val" />
Hidden Field
@Html.Hidden("Hidden1", "val")
Output:
<input id="Hidden1" name="Hidden1" type="hidden"
value="val" />
CheckBox
@Html.CheckBox("Checkbox1", false)
Output:
<input id="Checkbox1" name="Checkbox1"
type="checkbox" value="true" /> <input name="myCheckbox"
type="hidden" value="false" />
RadioButton
@Html.RadioButton("Radiobutton1", "val", true)
Output:
<input checked="checked" id="Radiobutton1"
name="Radiobutton1" type="radio" value="val" />
Drop-down list
@Html.DropDownList (“DropDownList1”, new SelectList(new []
{"Male", "Female"}))
Output:
<select id="DropDownList1" name="DropDownList1">
<option>M</option> <option>F</option> </select>
Multiple-select
Html.ListBox(“ListBox1”, new MultiSelectList(new [] {"Cricket",
"Chess"}))
Output:
<select id="ListBox1" multiple="multiple"
name="ListBox1"> <option>Cricket</option>
<option>Chess</option> </select>

2. Strongly Typed HTML Helpers


These helpers are used to render the most common types of HTML elements in
strongly typed view like as HTML text boxes, checkboxes etc. The HTML elements
are created based on model properties.
The strongly typed HTML helpers work on lambda expression. The model object
is passed as a value to lambda expression, and you can select the field or
property from model object to be used to set the id, name and value attributes
of the HTML helper. A list of most common strongly-typed html helpers is given
below:
HTML Element
Example
TextBox
@Html.TextBoxFor(m=>m.Name)
Output:
<input id="Name" name="Name" type="text"
value="Name-val" />
TextArea
@Html.TextArea(m=>m.Address , 5, 15, new{}))
Output:
<textarea cols="15" id="Address" name=" Address "
rows="5">Addressvalue</textarea>
Password
@Html.PasswordFor(m=>m.Password)
Output:
<input id="Password" name="Password"
type="password"/>
Hidden Field
@Html.HiddenFor(m=>m.UserId)
Output:
<input id=" UserId" name=" UserId" type="hidden"
value="UserId-val" />
CheckBox
@Html.CheckBoxFor(m=>m.IsApproved)
Output:
<input id="Checkbox1" name="Checkbox1"
type="checkbox" value="true" /> <input name="myCheckbox"
type="hidden" value="false" />
RadioButton
@Html.RadioButtonFor(m=>m.IsApproved, "val")
Output:
<input checked="checked" id="Radiobutton1"
name="Radiobutton1" type="radio" value="val" />
Drop-down list
@Html.DropDownListFor(m => m.Gender, new SelectList(new
[] {"Male", "Female"}))
Output:
<select id="Gender" name="Gender">
<option>Male</option> <option>Female</option>
</select>
Multiple-select
Html.ListBoxFor(m => m.Hobbies, new MultiSelectList(new []
{"Cricket", "Chess"}))
Output:
<select id="Hobbies" multiple="multiple"
name="Hobbies"> <option>Cricket</option>
<option>Chess</option> </select>

3. Templated HTML Helpers


These helpers figure out what HTML elements are required to render based on
properties of your model class. This is a very flexible approach for displaying data
to the user, although it requires some initial care and attention to set up. To
setup proper HTML element with Templated HTML Helper, make use of
DataType attribute of DataAnnitation class.
For example, when you use DataType as Password, A templated helper
automatically render Password type HTML input element.
Templated Helper
Example
Display
Renders a read-only view of the specified model property and
selects an appropriate HTML element based on property’s data
type and metadata.
Html.Display("Name")
DisplayFor
Strongly typed version of the previous helper
Html.DisplayFor(m => m. Name)
Editor
Renders an editor for the specified model property and selects
an appropriate HTML element based on property’s data type
and metadata.
Html.Editor("Name")
EditorFor
Strongly typed version of the previous helper
Html.EditorFor(m => m. Name)

3. Custom Html Helpers


You can also create your own custom helper methods by creating an extension
method on the HtmlHelper class or by creating static methods with in a utility class.
1. public static class CustomHelpers
2. {
3. //Submit Button Helper
4. public static MvcHtmlString SubmitButton(this HtmlHelper helper,
string
5. buttonText)
6. {
7. string str = "<input type=\"submit\" value=\"" + buttonText + "\"
/>";
8. return new MvcHtmlString(str);
9. }
10. //Readonly Strongly-Typed TextBox Helper
11. public static MvcHtmlString TextBoxFor<TModel, TValue>(this
12. HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>>
13. expression, bool isReadonly)
14. {
15. MvcHtmlString html = default(MvcHtmlString);
16.
17. if (isReadonly)
18. {
19. html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelpe
r,
20. expression, new { @class = "readOnly",
21. @readonly = "read-only" });
22. }
23. else
24. {
25. html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelpe
r,
26. expression);
27. }
28. return html;
29. }
30. }

S-ar putea să vă placă și