Documente Academic
Documente Profesional
Documente Cultură
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.
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. }
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.
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.
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.
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.
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.
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
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. }
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. }
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.
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.
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. }
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.
Advanced
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.
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.
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.
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.
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
http://example.com/Admin/Product/1
http://example.com/Admin/Product/SubAdmin/1
No Match Found
http://example.com/Admin/Product/SubAdmin/Add/1
No Match Found
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.
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.
Value
Description
Default
The default Asp.Net behavior is used to determine the session state behavior.
Disabled
ReadOnly
Required
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.
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.
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.
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 -
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.
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.
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. }
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#" })
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>