Sunday, 5 November 2017

MVC

MVC


-- MVC(Model View COntrollor) 
-- is open source web application framework.

 

Advantages of using asp.net mvc    

  • Views and controllers get connected automatically
  • Multiple GUI platforms supported
  • Platform-independent navigation to views
  • Easier to manage the complexity
  • Enables the full control over the rendered HTML.
  • Provides clean separation of concerns(SoC).
  • Enables Test Driven Development (TDD).
  • Easy integration with JavaScript frameworks.
  • Following the design of stateless nature of the web.
  • RESTful urls that enables SEO.



 3-tier Architecture  


    Camel type---à MyFirstApp(Each word first letter caps)
    <!DOCTYPE html>  -----------html5
    <meta charset=”utf-8”>avoid cross site scripting
    <meta name=”viewport” content=width=”device-width”> --Responsive
    Controller:
    - Default keyword (controller)followed by controller (ex: HomeController)
    - Controller Handle User Interaction logic
    - Every public method called as action method
    -Create properties prop doubletab

    View:
    - View means user interface or design
    - User interact with server.
    - view/currentcontrollerFolder/arguments
    - Action to view ----àviewData[“Test”]=”hi”;
    -viewBag---ViewBag.Title=”hfhfhf”;
    - Razor syntax--à@.....

    Model:
    Business data and Business logics layout




    1.viewResult---Render a complete web page
        Ex:Return view(model)
    2.PartialViewResult—render a section of webpage
    3.contentResult--- returns user defind,contents,xml
       Ex : Return content(“test”)
    4.jsonResult—return Json Result
      Ex:
         Var serial=”gfdghfh”;
         return Json(new {name=”serial”, value=serial},JsonRequestBehaviour.AllowGet)
    5.RedirectToRouteResult---redirect to another action
        Ex:Return RedirectToAction(“index”)
    What is the difference between each version of MVC 2, 3 , 4, 5 and 6?
    MVC 6
    ASP.NET MVC and Web API has been merged in to one.
    Dependency injection is inbuilt and part of MVC.
    Side by side - deploy the runtime and framework with your application
    Everything packaged with NuGet, Including the .NET runtime itself.
    New JSON based project structure.
    No need to recompile for every change. Just hit save and refresh the browser.
    Compilation done with the new Roslyn real-time compiler.
    vNext is Open Source via the .NET Foundation and is taking public contributions.
    vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.
    MVC 5
    One ASP.NET
    Attribute based routing
    Asp.Net Identity
    Bootstrap in the MVC template
    Authentication Filters
    Filter overrides
    MVC 4
    ASP.NET Web API
    Refreshed and modernized default project templates
    New mobile project template
    Many new features to support mobile apps
    Enhanced support for asynchronous methods
    MVC 3
    Razor
    Readymade project templates
    HTML 5 enabled templates
    Support for Multiple View Engines
    JavaScript and Ajax
    Model Validation Improvements
    MVC 2
    Client-Side Validation
    Templated Helpers
    Areas
    Asynchronous Controllers
    Html.ValidationSummary Helper Method
    DefaultValueAttribute in Action-Method Parameters
    Binding Binary Data with Model Binders
    DataAnnotations Attributes
    Model-Validator Providers
    New RequireHttpsAttribute Action Filter
    Templated Helpers
    Display Model-Level Errors

    What are HTML helpers in MVC?

    HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.
    <%= Html.TextBox("LastName") %>
    For checkbox below is the HTML helper code. In this way we have HTML helper methods for every HTML control that exists.
    <%= Html.CheckBox("Married") %>

    What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”?

    Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t. Below is a simple HTML code which just creates a simple textbox with “CustomerCode” as name.
    Html.TextBox("CustomerCode")
    Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘CustomerCode” from object “m”.
    Html.TextBoxFor(m => m.CustomerCode)
    In the same way we have for other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.

    Where is the route mapping code written?

    The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.

    Can we map multiple URL’s to the same action?

    Yes, you can, you just need to make two entries with different key names and specify the same controller and action.

    How can we navigate from one view to another using a hyperlink?

    By using the ActionLink method as shown in the below code. The below code will create a simple URL which helps to navigate to the “Home” controller and invoke the GotoHome action.
    <%= Html.ActionLink("Home","Gotohome") %> 
     

    How can we maintain sessions in MVC?

    Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.

    How can we maintain sessions in MVC?

    Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.

    What is the difference between tempdata, viewdata, and viewbag?

    Figure: Difference between tempdata, viewdata, and viewbag
    • Temp data - Helps to maintain data when you move from one controller to another controller or from one action to another action. In other words when you redirect, tempdata helps to maintain data between those redirects. It internally uses session variables.
    • View data - Helps to maintain data when you move from controller to view.
    • View Bag - It’s a dynamic wrapper around view data. When you use Viewbag type, casting is not required. It uses the dynamickeyword internally.
    Figure: dynamic keyword
    • Session variables - By using session variables we can maintain data from any entity to any entity.
    • Hidden fields and HTML controls - Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.
    Below is a summary table which shows the different mechanisms for persistence.
    Maintains data betweenViewData/ViewBagTempDataHidden fieldsSession
    Controller to ControllerNoYesNoYes
    Controller to ViewYesNoNoYes
    View to ControllerNoNoYesYes

    What is difference between TempData and ViewData ?

    “TempData” maintains data for the complete request while “ViewData” maintains data only from Controller to the view.

    Does “TempData” preserve data in the next request also?

    “TempData” is available through out for the current request and in the subsequent request it’s available depending on whether “TempData” is read or not.
    So if “TempData” is once read it will not be available in the subsequent request.

    What are partial views in MVC?

    Partial view is a reusable view (like a user control) which can be embedded inside other view. For example let’s say all your pages of your site have a standard structure with left menu, header, and footer as shown in the image below.
    Figure: Partial views in MVC
    For every page you would like to reuse the left menu, header, and footer controls. So you can go and create partial views for each of these items and then you call that partial view in the main view.

    What is Razor in MVC?

    It’s a light weight view engine. Till MVC we had only one view type, i.e., ASPX. Razor was introduced in MVC 3.

    Why Razor when we already have ASPX?

    Razor is clean, lightweight, and syntaxes are easy as compared to ASPX. For example, in ASPX to display simple time, we need to write:
    <%=DateTime.Now%> 
    In Razor, it’s just one line of code:
    @DateTime.Now

    So which is a better fit, Razor or ASPX?

    As per Microsoft, Razor is more preferred because it’s light weight and has simple syntaxes.

    How can you do authentication and authorization in MVC?

    You can use Windows or Forms authentication for MVC.

    How to implement Windows authentication for MVC?

    For Windows authentication you need to modify the web.config file and set the authentication mode to Windows.
    <authentication mode="Windows"/>
    <authorization>
    <deny users="?"/>
    </authorization> 
    Then in the controller or on the action, you can use the Authorize attribute which specifies which users have access to these controllers and actions. Below is the code snippet for that. Now only the users specified in the controller and action can access it.
    [Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
    public class StartController : Controller
    {
        //
        // GET: /Start/
        [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
        public ActionResult Index()
        {
            return View("MyView");
        }
    } 

    How do you implement Forms authentication in MVC?

    Forms authentication is implemented the same way as in ASP.NET. The first step is to set the authentication mode equal to Forms. The loginUrl points to a controller here rather than a page.
    <authentication mode="Forms">
    <forms loginUrl="~/Home/Login"  timeout="2880"/>
    </authentication> 
    We also need to create a controller where we will check if the user is proper or not. If the user is proper we will set the cookie value.
    public ActionResult Login()
    {
        if ((Request.Form["txtUserName"] == "Shiv") && 
              (Request.Form["txtPassword"] == "Shiv@123"))
        {
            FormsAuthentication.SetAuthCookie("Shiv",true);
            return View("About");
        }
        else
        {
            return View("Index");
        }
    } 
    All the other actions need to be attributed with the Authorize attribute so that any unauthorized user making a call to these controllers will be redirected to the controller (in this case the controller is “Login”) which will do the authentication.
    [Authorize]
    PublicActionResult Default()
    {
    return View();
    }
    [Authorize]
    publicActionResult About()
    {
    return View();
    } 
     

    What are the different types of results in MVC?

    Note: It’s difficult to remember all the 12 types. But some important ones you can remember for the interview are ActionResultViewResult, and JsonResult. Below is a detailed list for your interest:
    There 12 kinds of results in MVC, at the top is the ActionResult class which is a base class that can have 11 subtypes 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 ViewData 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 are the different types of action filters?

    1. Authorization filters
    2. Action filters
    3. Result filters
    4. Exception filters

    How to send result back in JSON format in MVC

    In MVC, we have the JsonResult class by which we can return back data in JSON format. Below is a simple sample code which returns back a Customer object in JSON format using JsonResult.
    public JsonResult getCustomer()
    {
        Customer obj = new Customer();
        obj.CustomerCode = "1001";
        obj.CustomerName = "Shiv";
        return Json(obj,JsonRequestBehavior.AllowGet);
    }
    Below is the JSON output of the above code if you invoke the action via the browser.


    Protocols in MVC

     GET,    POST,    PUT,    DELETE

    No comments:

    Post a Comment