MVC

1.      Features
a.      MVC 6
                                                              i.      Dependency Injection
                                                            ii.      Save and refresh browser
                                                          iii.      New JSON based project structure
                                                           iv.      Everything packed with NuGet
b.      MVC 5
                                                              i.      Attribute based routing
                                                            ii.      Bootstrap in MVC template
                                                          iii.      ASP.NET Identity
c.       MVC 4
                                                              i.      Web API
                                                            ii.      New features for mobile development
                                                          iii.      Mobile project template
d.      MVC 3
                                                              i.      RAZOR
                                                            ii.      Readymade project templates
                                                          iii.      HTML5 support
                                                           iv.      JavaScript and AJAX support
e.      MVC 2
                                                              i.      Client Side validation
                                                            ii.      Validation summary
                                                          iii.      Data Annotations
                                                           iv.      Model Validation
2.      Routing
a.      Register from Application_Start() of Global.asax file
b.      Mapping written in RouteConfig.cs file in App_Start folder
c.       Route.MapRoute(
“View”, // Route Name
“view/ViewCustomer/{id}”, // URL pattern with parameter
New {controller=”Customer”, action=”DisplayCustomer”, id= UrlParameter.Optional}
);
3.      Attribute based routing
a.      Introduced in MVC 5
b.      Defining URL in Route attribute on top of method
c.       [Route(“Users/About”)]
d.      Multiple Route attributes are allowed          
4.      Validation
a.      Using data annotations in model, Like [Required(ErrorMessage=”This is required”)]
b.      To show validation messages, <%= Html.ValidationMessageFor(m=>m.SomeField)%>
c.       To check validation in controller, ModelState.IsValid
d.      <%= Html.ValidationSummary()%>, to show all error messages
e.      ModelState[“Email”].Errors[0].ErrorMessage, to get error message
f.        TryUpdateMode(myModel), to validate your model
g.      ModelState.AddModelError(“FirstName”,”This is my error”), to add custom error
h.      <%= Html.EnableClientValidation();%>, to enable client side validation with annotations
i.        [StringLength(150)]
j.        [RegularExpression(@”[A-Za-z]”)]
k.       [Range(10,25)]
l.        [Compare(“MyPasswordField”)], use this on second field to compare with first
m.     
5.      Navigation
a.      View to view : <%= Html.ActionLink(“HomeController”,”GoToHomeFuntion”)%>
b.      Controller to view : return View(“User/DisplayUser”,UserID);
6.      Session Management
a.      View Data : Controller to view
b.      View Bag : Controller to view, wrapper to View Data, No casting required
c.       Temp Data : Controller to controller,
7.      Partial View (.ascx)
a.      Similar to User control in ASP.NET
b.      While creating view, check partial view checkbox
c.       <%=Html.RenderPartial(“MyView”)%> , to add partial view in view
8.       In ASP : <%=DateTime,Now%>, In Razor : @DateTime.Now
9.      Authentication
a.      Windows:
                                                              i.      In Web.config, <authentication mode=”windows”> <authorization><deny users=”?”></authorization>
                                                            ii.      On controller oraction, [Authorize(Users=@”WIN-bdsfbhb\Admin”)]
b.      Forms Authentication:
                                                              i.      In Web.config, <authentication mode=”Forms”><forms loginurl=”~/Login” timeout=2000/></authentication>
                                                            ii.      In some login action for first  time, FormsAuthentication.SetAuthCookie(“Vipul”,true);
                                                          iii.      Other action will have [Authorize] attribute
                                                           iv.       
10.  ActionResult is abstract class having several derived classes like:
a.      ViewResult, having method View()
b.      JsonResult, having method Json()
c.       FileStreamResult
d.      RedirectResult
11.  ActionFilters
a.      This helps to write login while executing some action or after executing some action
b.      While executing: Cancel, Add extra data
c.       After executing: Log, Post-Processing
d.      Two ways:
                                                              i.      Inline: inherit IActionFiler interface in controller and add IActionFilter.OnActionExecuted(ActionExecutedContext context) and IActionFiler.OnActionExecuting(ActionExecutingContext context) methods – This type is not useful as it cannot be reused
                                                            ii.      ActionFilterAttribute: rather creating controller create Attribute (same as controller), inherit IActionFilter and ActionFilterAttribute, add above mentioned two methods (executing and executed), add [MyActionAttribute] attribute on any controller. MyActionAttribute is attribute that we have created
12.  Different filters (Same execution sequence as below):
a.      Authorization Filter
b.      Action Filter
c.       Response Filter
d.      Exception Filter
13.  WCF VS Web API
a.      WCF follow SOAP, Web API follow REST principles
b.      WCF is heavy, Web API is light weight
c.       WCF works with any protocol, Web API works with HTTP only
d.      For WCF we need some proxy to parse WSDL, Web API returns simple strings, JSONs or XMLs, so easy to process
e.      WCF introduced to implement SOA not for REST, Web API are developed intending REST, so preferred
14.  Request.HttpMethod, to get type of call to controller
15.  Bundling
a.      Combining multiple files into single entity thus minimize multiple server requests
b.      In App_Start folder, in BundleConfig.cs file, add below code to bundle al .js files
Public static void RegisterBundles(BndleCollection bundles)
{
            Bundles.Add(new ScriptBundle(“~Scripts/MyScripts”).Include(“~/Scripts/*.js”));
            BundleTable.EnableOptimizations = true;
}
c.       To use all bundles files in view, <%= Scripts.Render(“~/Scripts/MyScripts”)%>
16.  Minification reduces the size of scripts and CSS by removing blank spaces, comments etc. When we do bundling by default if minifies the files.
17.  Area in MVC used to organize project into independent modules, each area has its own Module, View and controller folders
18.  MVC Scaffolding is a technique in which MVC templates helps us to auto generate CRUD code with view, controller and model also. Internally it uses EntityFramework.
19.  Exception Handling in MVC
a.      Override ‘OnException’ event and set result to view which you want
Protected override void OnException(ExceptionContext fiterContext)
{
            Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception,”Controller”,”Action”);
filterContext.Result = new ViewResult()
{
            ViewName = “Error”,
ViewData = new ViewDataDictionary(model);         
}
}
b.      To display exception on view, @Model.Exception;

20.  CSRF (Cross Site Request Forgery), is a type of web attack in which attacker sends request as trusted user (for example, we always see ads saying you win some amount fill bank details). To identify trusted source MVC uses token, each time user needs to send forgery token with server request.