Friday, 29 April 2016

MVC



ASP.Net MVC is a pattern which is used to split the application's implementation logic into three components i.e. models, views, and controllers.
Model : It is basically a business entity which is used to represent the application data. Controller : The Request which is sent by the user always scatters through controller and it's responsibility is to redirect to the specific view using View () method. View : it's the presentation layer of ASP.Net MVC.
Following are features added newly : Mobile templates Added ASP.NET Web API template for creating REST based services. Asynchronous controller task support. Bundling of the java scripts. Segregating the configs for ASP.Net MVC routing, Web API, Bundle etc.
Below are the processed followed in the sequence -
  • App initializWhat is Separation of Concerns in ASP.NET ASP.Net MVCation
  • Routing
  • Instantiate and execute controller
  • Locate and invoke controller action
  • Instantiate and render view.
  • Provides a clean separation of concerns among UI (Presentation layer), model (Transfer objects/Domain Objects/Entities) and Business Logic (Controller).
  • Easy to UNIT Test.
  • Improved reusability of model and views. We can have multiple views which can point to the same model and vice versa.
  • Improved structuring of the code.
It is the process of breaking the program into various distinct features which overlaps in functionality as little as possible. ASP.Net MVC pattern concerns on separating the content from presentation and data-processing from content.
Razor is the first major update to render HTML in ASP.Net MVC 3. Razor was designed specifically for view engine syntax. Main focus of this would be to simplify and code-focused templating for HTML generation. Below is the sample of using Razor:
@model ASP.Net MVCMusicStore.Models.Customer
@{ViewBag.Title = "Get Customers";}
< div class="cust"> <h3><em>@Model.CustomerName</<em> </<h3><div>
This is a general term that conveys a general philosophy, similar to the term REST (Representational State Transfer). Unobtrusive JavaScript doesn't inter mix JavaScript code in your page markup. Eg : Instead of using events like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by their ID or class based on the HTML5 data- attributes.
View Model is a plain class with properties, which is used to bind it to strongly typed view. View Model can have the validation rules defined for its properties using data annotations.
Routing is a pattern matching mechanism of incoming requests to the URL patterns which are registered in route table. Class : "UrlRoutingModule" is used for the same process.
Actions are the methods in Controller class which is responsible for returning the view or json data. Action will mainly have return type : "ActionResult" and it will be invoked from method : "InvokeAction()" called by controller.
ASP.NET Web API supports this type routing. This is introduced in ASP.Net MVC5. In this type of routing, attributes are being used to define the routes. This type of routing gives more control over classic URI Routing. Attribute Routing can be defined at controller level or at Action level like :
[Route("{action = TestCategoryList}")] - Controller Level
[Route("customers/{TestCategoryId:int:min(10)}")] - Action Level
Just add @Model.CustomerName the method : "MapASP.Net MVCAttributeRoutes()" to enable attribute routing as shown below:
public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //enabling attribute routing
        routes.MapASP.Net MVCAttributeRoutes();
        //convention-based routing
        routes.MapRoute
        (
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Customer", action = "GetCustomerList", id = UrlParameter.Optional }
        );
    }
JavaScript Object Notation (JSON) binding support started from ASP.Net MVC3 onwards via the new JsonValueProviderFactory, which allows the action methods to accept and model-bind data in JSON format. This is useful in Ajax scenarios like client templates and data binding that need to post data back to the server.
Dependency Resolver again has been introduced in ASP.Net MVC3 and it is greatly simplified the use of dependency injection in your applications. This turn to be easier and useful for decoupling the application components and making them easier to test and more configurable.
"BundleConfig.cs" in ASP.Net MVC4 is used to register the bundles by the bundling and minification system. Many bundles are added by default including jQuery libraries like - jquery.validate, Modernizr, and default CSS references.
Method : "RegisterRoutes()" is used for registering the routes which will be added in "Application_Start()" method of global.asax file, which is fired when the application is loaded or started.
Below are the important namespaces used in ASP.Net MVC -
  • System.Web.ASP.Net MVC
  • System.Web.ASP.Net MVC.Ajax
  • System.Web.ASP.Net MVC.Html
  • System.Web.ASP.Net MVC.Async
Viewdata contains the key, value pairs as dictionary and this is derived from class : "ViewDataDictionary". In action method we are setting the value for viewdata and in view the value will be fetched by typecasting.
ViewBag is a wrapper around ViewData, which allows to create dynamic properties. Advantage of viewbag over viewdata will be : In ViewBag no need to typecast the objects as in ViewData. ViewBag will take advantage of dynamic keyword which is introduced in version 4.0. But before using ViewBag we have to keep in mind that ViewBag is slower than ViewData.
TempData is again a key, value pair as ViewData. This is derived from "TempDataDictionary" class. TempData is used when the data is to be used in two consecutive requests, this could be between the actions or between the controllers. This requires typecasting in view.
HTML Helpers are like controls in traditional web forms. But HTML helpers are more lightweight compared to web controls as it does not hold viewstate and events. HTML Helpers returns the HTML string which can be directly rendered to HTML page. Custom HTML Helpers also can be created by overriding "HtmlHelper" class.
AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs the request asynchronously and these are extension methods of AJAXHelper class which exists in namespace - System.Web.ASP.Net MVC.
Below are the options in AJAX helpers :
  • Url : This is the request URL.
  • Confirm : This is used to specify the message which is to be displayed in confirm box.
  • OnBegin : Javascript method name to be given here and this will be called before the AJAX request.
  • OnComplete : Javascript method name to be given here and this will be called at the end of AJAX request.
  • OnSuccess - Javascript method name to be given here and this will be called when AJAX request is successful.
  • OnFailure - Javascript method name to be given here and this will be called when AJAX request is failed.
  • UpdateTargetId : Target element which is populated from the action returning HTML.
Layout pages are similar to master pages in traditional web forms. This is used to set the common look across multiple pages. In each child page we can find : /p>
@{
Layout = "~/Views/Shared/TestLayout1.cshtml";
}
This indicates child page uses TestLayout page as it's master page.
Section are the part of HTML which is to be rendered in layout page. In Layout page we will use the below syntax for rendering the HTML :
@RenderSection("TestSection")
And in child pages we are defining these sections as shown below :
@section TestSection{
<h1>Test Content<h1>
}
If any child page does not have this section defined then error will be thrown so to avoid that we can render the HTML like this :
@RenderSection("TestSection", required: false)
RenderBody is like ContentPlaceHolder in web forms. This will exist in layout page and it will render the child pages/views. Layout page will have only one RenderBody() method. RenderPage also exists in Layout page and multiple RenderPage() can be there in Layout page.
This page is used to make sure common layout page will be used for multiple views. Code written in this file will be executed first when application is being loaded.
Below are the methods used to render the views from action -
  • View() : To return the view from action.
  • PartialView() : To return the partial view from action.
  • RedirectToAction() : To Redirect to different action which can be in same controller or in different controller.
  • Redirect() : Similar to "Response.Redirect()" in webforms, used to redirect to specified URL.
  • RedirectToRoute() : Redirect to action from the specified URL but URL in the route table has been matched.
ActionResult is used to represent the action method result. Below are the subtypes of ActionResult :
  • ViewResult
  • PartialViewResult
  • RedirectToRouteResult
  • RedirectResult
  • JavascriptResult
  • JSONResult
  • FileResult
  • HTTPStatusCodeResult
In ASP.Net MVC all public methods have been treated as Actions. So if you are creating a method and if you do not want to use it as an action method then the method has to be decorated with "NonAction" attribute as shown below :
[NonAction]
public void TestMethod()
{
// Method logic
}
"ActionName" attribute can be used for changing the action name. Below is the sample code snippet to demonstrate more :
[ActionName("TestActionNew")]
public ActionResult TestAction()
    {
        return View();
    }
So in the above code snippet "TestAction" is the original action name and in "ActionName" attribute, name - "TestActionNew" is given. So the caller of this action method will use the name "TestActionNew" to call this action.
Unlike code expressions that are evaluated and sent to the response, it is the blocks of code that are executed. This is useful for declaring variables which we may be required to be used later.
@{
 int x = 123;
 string y = "aa";
 }
The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used during the request of the Web page.
Create a JavaScript method:
function DrpIndexChanged() { }
Invoke the method:
< %:Html.DropDownListFor(x => x.SelectedProduct, new SelectList(Model.Customers, "Value", "Text"), "Please Select a Customer", new { id = "ddlCustomers", onchange=" DrpIndexChanged ()" })%>
Data annotations are attributes which can be found in the "System.ComponentModel.DataAnnotations" namespace. These attributes will be used for server-side validation and client-side validation is also supported. Four attributes - Required, String Length, Regular Expression and Range are used to cover the common validation scenarios.
This method is used to render the specified partial view as an HTML string. This method does not depend on any action methods. We can use this like below : @Html.Partial("TestPartialView")
Result of the method : "RenderPartial" is directly written to the HTML response. This method does not return anything (void). This method also does not depend on action methods. RenderPartial() method calls "Write()" internally and we have to make sure that "RenderPartial" method is enclosed in the bracket. Below is the sample code snippet : @{Html.RenderPartial("TestPartialView"); }
"RouteConfig.cs" holds the routing configuration for ASP.Net MVC. RouteConfig will be initialized on Application_Start event registered in Global.asax.
Scaffolding in ASP.NET ASP.Net MVC is used to generate the Controllers,Model and Views for create, read, update, and delete (CRUD) functionality in an application. The scaffolding will be knowing the naming conventions used for models and controllers and views.
Below are the types of scaffoldings :
  • Empty
  • Create
  • Delete
  • Details
  • Edit
  • List
Yes we can share a view across multiple controllers. We can put the view in the "Shared" folder. When we create a new ASP.Net MVC Project we can see the Layout page will be added in the shared folder, which is because it is used by multiple child pages.
  • Name - This is the name of the route.
  • URL Pattern : Placeholders will be given to match the request URL pattern.
  • Defaults :When loading the application which controller, action to be loaded along with the parameter.
Using this default route - {resource}.axd/{*pathInfo}, we can prevent the requests for the web resources files like - WebResource.axd or ScriptResource.axd from passing to a controller.
Yes we can add constraints to route in following ways :
  • Using Regular Expressions
  • Using object which implements interface - IRouteConstraint.
Below are the two types of extensions razor view can have :
  • .cshtml : In C# programming language this extension will be used.
  • .vbhtml - In VB programming language this extension will be used.
PartialView is similar to UserControls in traditional web forms. For re-usability purpose partial views are used. Since it's been shared with multiple views these are kept in shared folder. Partial Views can be rendered in following ways :
  • Html.Partial()
  • Html.RenderPartial()
Below is the sample code snippet to add css to razor views : < link rel="StyleSheet" href="/@Href(~Content/Site.css")" type="text/css"/>
No. We cannot add the test cases in Visual Studio Express edition it can be added only in Professional and Ultimate versions of Visual Studio.
Glimpse is an open source tool for debugging the routes in ASP.Net MVC. It is the client side debugger. Glimpse has to be turned on by visiting to local url link - http://localhost:portname//glimpse.axd This is a popular and useful tool for debugging which tracks the speed details, url details etc.
Action Filters allow us to execute the code before or after action has been executed. This can be done by decorating the action methods of controls with ASP.Net MVC attributes.
Below are some action filters used :
  • Authentication
  • Authorization
  • HandleError
  • OutputCache
This can be done in following way : Use class : "HttpRequestBase" and use the method : "HttpMethod" to determine the action request type.
Whenever validation fails it will be tracked in ModelState. By using property : IsValid it can be determined. In Server code, check like this :
if(ModelState.IsValid){
     // No Validation Errors
}
In Web.Config there are tags called : "ClientValidationEnabled" and "UnobtrusiveJavaScriptEnabled". We can set the client side validation just by setting these two tags "true", then this setting will be applied at the application level.
< add key="ClientValidationEnabled" value="true" />
< add key="UnobtrusiveJavaScriptEnabled" value="true" />
For Model Binding we will use class called : "ModelBinders", which gives access to all the model binders in an application. We can create a custom model binders by inheriting "IModelBinder".
Exception Handling is made simple in ASP.Net MVC and it can be done by just overriding "OnException" and set the result property of the filtercontext object (as shown below) to the view detail, which is to be returned in case of exception.
protected overrides void OnException(ExceptionContext filterContext)
    {
    }
If Tempdata is assigned in the current request then it will be available for the current request and the subsequent request and it depends whether data in TempData read or not. If data in Tempdata is read then it would not be available for the subsequent requests.
As explained above in case data in Tempdata has been read in current request only then "Keep" method has been used to make it available for the subsequent request.
@TempData["TestData"];
TempData.Keep("TestData");
Similar to Keep method we have one more method called "Peek" which is used for the same purpose. This method used to read data in Tempdata and it maintains the data for subsequent request.
string A4str = TempData.Peek("TT").ToString();
Area is used to store the details of the modules of our project. This is really helpful for big applications, where controllers, views and models are all in main controller, view and model folders and it is very difficult to manage.
When we have created an area make sure this will be registered in "Application_Start" event in Global.asax. Below is the code snippet where area registration is done :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
}
To create reusable widgets child actions are used and this will be embedded into the parent views. In ASP.Net MVC Partial views are used to have reusability in the application. Child action mainly returns the partial views.
"ChildActionOnly" attribute is decorated over action methods to indicate that action method is a child action. Below is the code snippet used to denote the child action :
[ChildActionOnly]
public ActionResult MenuBar()
{
//Logic here
return PartialView();
}
it's a design pattern and is used for developing loosely couple code. This is greatly used in the software projects. This will reduce the coding in case of changes on project design so this is vastly used.
TDD is a methodology which says, write your tests first before you write your code. In TDD, tests drive your application design and development cycles. You do not do the check-in of your code into source control until all of your unit tests pass.
Below are the tools used for unit testing :
  • NUnit
  • xUnit.NET
  • Ninject 2
  • Moq
REST is an architectural style which uses HTTP protocol methods like GET, POST, PUT, and DELETE to access the data. ASP.Net MVC works in this style. In ASP.Net MVC 4 there is a support for Web API which uses to build the service using HTTP verbs.
We can use dataannotations for validation in ASP.Net MVC. If we want to use validation during runtime using Jquery then we can use Jquery plugins for validation. Eg: If validation is to be done on customer name textbox then we can do as :
$('#CustomerName').rules("add", {
required: true,
minlength: 2,
messages: {
required: "Please enter name",
minlength: "Minimum length is 2"
}
});
Below is the scenario and the solution to solve multiple submit buttons issue. Scenario :
@using (Html.BeginForm("MyTestAction","MyTestController")
{
    <input type="submit" value="MySave" />
    <input type="submit" value="MyEdit" />
}
Solution :
Public ActionResult MyTestAction(string submit) //submit will have value either "MySave" or "MyEdit"
{
    // Write code here
}
  • Display Templates : These are model centric. Meaning it depends on the properties of the view model used. It uses convention that will only display like divs or labels.
  • Edit Templates : These are also model centric but will have editable controls like Textboxes.
  • Partial View : These are view centric. These will differ from templates by the way they render the properties (Id's) Eg : CategoryViewModel has Product class property then it will be rendered as Model.Product.ProductName but in case of templates if we CategoryViewModel has List then @Html.DisplayFor(m => m.Products) works and it renders the template for each item of this list.
No. We can't set unlimited length for property maxJsonLength. Default value is - 102400 and maximum value what we can set would be : 2147483644.
Yes. We can use the razor code in javascript in cshtml by using <text> element.
< script type="text/javascript">
@foreach (var item in Model) {
< text >
//javascript goes here which uses the server values
< text >
}
< script>
Below is the code snippet to return string from action method :
public ActionResult TestAction() {
return Content("Hello Test !!");
}
Below is the code snippet to return string from action method :
public ActionResult TestAction() {
return JSON(new { prop1 = "Test1", prop2 = "Test2" });
}

What is the difference between “ActionResult” and “ViewResult”?
“ActionResult” is an abstract class while “ViewResult” derives from “ActionResult” class.
“ActionResult” has several derived classes like “ViewResult” ,”JsonResult” , “FileStreamResult” and so
on.
“ActionResult” can be used to exploit polymorphism and dynamism. So if you are returning different
types of view dynamically “ActionResult” is the best thing. For example in the below code snippet you
can see we have a simple action called as “DynamicView”. Depending on the flag (“IsHtmlView”) it will
either return “ViewResult” or “JsonResult”.

What are the different types of results in MVC?
12 types
Important are “ActionResult”, “ViewResult” and “JsonResult”.
At the top is “ActionResult”class which is a base class that can have 11 subtype’s as listed below,
1. ViewResult - Renders a specified view to the response stream
2. PartialViewResult - Renders a specified partial view to the response stream
3. EmptyResult - An empty response is returned
4. RedirectResult - Performs an HTTP redirection to a specified URL
5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the
routing engine, based on given route data
6. JsonResult - Serializes a given object to JSON format
7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
8. ContentResult - Writes content to the response stream without requiring a view
9. FileContentResult - Returns a file to the client
10. FileStreamResult - Returns a file to the client, which is provided by a Stream
11. FilePathResult - Returns a file to the client


What is Action filter in MVC?
Actions are public methods in a controller. Action filters are attributes, which can be applied either on a controller or on controller action method, which allows us to add pre and post processing logic to the actions methods
So, in short action filters allows us to execute some custom code, either just before an action executed 
Or immediately after an action method completes execution.

The ASP.NET MVC framework supports four different types of filters
1.       Authorization filters
2.       Action filters
3.       Result filters
4.       Exception filters
Filters are executed in the order listed above.

For example, authorization filters are always executed before action filters and exception filters are always executed after every other type of filter.


Authorization filters:  Implements IAuthorizationFilter and are used to implement authentication and authorization for controller actions. Ex. [Authorize]
Action filters: Implements IActionFilter and contain logic that is executed before and after a controller action executes.
Result filters: Implements IResultFilter and contain logic that is executed before and after a view result is executed.
Exception filters: Implements IExceptionFilter and this is the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.
Note: Each different type of filter is executed in a particular order. If you want to control the order in which filters of the same type are executed then you can set a filter's order property.

What is Bundling and minification in MVC?
Bundling and minification helps us to improve request load time of a page thus increasing
performance.

How does bundling increase performance?
Web projects always need CSS and script files. Bundling helps us to combine to multiple
javascript and CSS file in to a single entity thus minimizing multiple requests in to a single
request.

How do we implement bundling in MVC ?
Open the “BundleConfig.cs” from the “App_Start” folder.
In the “BundleConfig.cs” add the JS files which you want bundle in to single entity in to the
bundles collection as fallows

BundleConfig.cs

public class BundleConfig
{
                public static void RegisterBundles(BundleCollection bundles)
                {
                 bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include("~/Scripts/*.js"));
                 BundleTable.EnableOptimizations = true;
                }
}
ASPX or RAZOR view.
<%= Scripts.Render("~/Scripts/MyScripts") %>

Explain minification and how to implement the same ?
Minification is another such performance improvement technique in which it optimizes the javascript, css code by shortening the variable names, removing unnecessary white spaces, line breaks and comments, etc. This in turn reduces the file size and helps the application to load faster.

How to implement minification ?
When you implement bundling, minification is implemented by itself.

Explain the concept of View Model in MVC ?
A view model is a simple class which represents data to be displayed on the view.
ex: we have a user model like
public class User
{
                UserId,
                UserName,
                EmailAddress,
                Password
}

On a user register page we have additional check of Confirm Password
So create UserRegister

public class UserRegisterViewModel
{
                UserId,
                UserName,
                EmailAddress,
                Password,
                ConfirmPassword
}

How can we use two ( multiple) models with a single view?
Create viewmodel like
public class CustOrderVM
{
                public Customer cust = new Customer();
                public Order Ord = new Order();
}

view
<%= model.cust.Name %>
<%= model.Ord.Number %>


Understanding the MVC Application Execution Process

.NET Framework 4
Requests to an ASP.NET MVC-based Web application first pass through the UrlRoutingModule object, which is an HTTP module. This module parses the request and performs route selection. The UrlRoutingModule object selects the first route object that matches the current request. (A route object is a class that implements RouteBase, and is typically an instance of the Route class.) If no routes match, the UrlRoutingModule object does nothing and lets the request fall back to the regular ASP.NET or IIS request processing.
From the selected Route object, the UrlRoutingModule object obtains an object that implements the IRouteHandler interface and that is associated with the Route object. Typically, in an MVC application, this will be an instance of the MvcRouteHandler class. The MvcRouteHandler instance creates an MvcHandler object that implements the IHttpHandler interface. The MvcHandler object then selects the controller that will ultimately handle the request. For more information, see ASP.NET Routing.
NoteNote
When an ASP.NET MVC Web application runs in IIS 7.0, no file name extension is required for MVC projects. However, in IIS 6.0, the handler requires that you map the .mvc file name extension to the ASP.NET ISAPI DLL.
The UrlRoutingModule and MvcRouteHandler classes are the entry points to the ASP.NET MVC framework. They perform the following actions:
  • Select the appropriate controller in an MVC Web application.
  • Obtain a specific controller instance.
  • Call the controller's Execute method.
The following table lists the stages of execution for an MVC Web project.
Stage
Details
Receive first request for the application
In the Global.asax file, Route objects are added to the RouteTable object.
Perform routing
The UrlRoutingModule module uses the first matching Route object in the RouteTable collection to create the RouteData object, which it then uses to create a RequestContext object.
Create MVC request handler
The MvcRouteHandler object creates an instance of the MvcHandler class and passes the RequestContext instance to the handler.
Create controller
The MvcHandler object uses the RequestContext instance to identify the IControllerFactory object (typically an instance of theDefaultControllerFactory class) to create the controller instance with.
Execute controller
The MvcHandler instance calls the controller's Execute method.
Invoke action
For controllers that inherit from the ControllerBase class, the ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method.
Execute result
The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The built-in result types that can be executed include the following: ViewResult (which renders a view and is the most-often used result type), RedirectToRouteResultRedirectResultContentResultJsonResultFileResult, and EmptyResult.

No comments:

Post a Comment