Sunday 12 February 2017

Interview question one line on Asp.net MVC

Sl No Questions Keyword Answer Example
1 What is MVC (Model view controller)? MVC is an architectural pattern which separates the representation and user interaction. It’s divided into three broader sections, Model, View, and Controller.
2 Explain MVC application life cycle?
Creating the request object: -The request object creation has four major steps. Below is the detail explanation of the same.

Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.

Step 2 Fetch route: - Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.

Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext” object.

Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.

Creating Response object: - This phase has two steps executing the action and finally sending the response as a result to the view

3 Is MVC suitable for both Windows and web applications? MVP 
4 What are the benefits of using MVC? There are two big benefits of MVC:

Separation of concerns is achieved as we are moving the code-behind to a separate class file.
Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple .NET class.
5 Is MVC different from a three layered architecture?
6 What is the latest version of MVC? MVC 6 is the latest version which is also termed as ASP VNEXT
7 What is the difference between each version of MVC 2, 3 , 4, 5 and 6?
8 What are HTML helpers in MVC?
9 What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”? “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t Html.TextBox("CustomerCode")

Html.TextBoxFor(m => m.CustomerCode)
10 What is routing in MVC? Routing helps you to define a URL structure and map the URL with the controller routes.MapRoute(
               "View", // Route name
               "View/ViewCustomer/{id}", // URL with parameters
               new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults
11 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
12 Can we map multiple URLs 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.
13 Explain attribute based routing in MVC? "Route" attribute  public class HomeController : Controller
{
       [Route("Users/about")]
       public ActionResult GotoAbout()
       {
           return View();
       }
}
14 What is the advantage of defining route structures in the code? public class HomeController : Controller
{
       [Route("Users/about")]
       [Route("Users/WhoareWe")]
       [Route("Users/OurTeam")]
       [Route("Users/aboutCompany")]
       public ActionResult GotoAbout()
       {
           return View();
       }
}
15 How can we navigate from one view to other view using a hyperlink? <%= Html.ActionLink("Home","Gotohome") %>
16 How can we restrict MVC actions to be invoked only by GET or POST? Decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls [HttpGet]
public ViewResult DisplayCustomer(int id)
{
    Customer objCustomer = Customers[id];
    return View("DisplayCustomer",objCustomer);
17 How can we maintain sessions in MVC? Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag
18 What is the difference between tempdata, viewdata, and viewbag? Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag
19 What is difference between TempData and ViewData ? “TempData” maintains data for the complete request while “ViewData” maintains data only from Controller to the view.
20 Does “TempData” preserve data in the next request also? “TempData” is once read it will not be available in the subsequent request
21 What is the use of Keep and Peek in “TempData”? If we want “TempData” to be read and also available in the subsequent request then after reading we need to call “Keep”

The more shortcut way of achieving the same is by using “Peek”. 

 @TempData[“MyData”];
TempData.Keep(“MyData”);

string str = TempData.Peek("Td").ToString();
22 What are partial views in MVC? Partial view is a reusable view (like a user control) which can be embedded inside other view.
23 How do you create a partial view and consume it? <body>
<div>
       <% Html.RenderPartial("MyView"); %>
</div>
</body>
24 How can we do validations in MVC?
25 Can we display all errors in one go?
26 How can we enable data annotation validation on the client side?
27 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.
28 Why Razor when we already have ASPX? In Razor, it’s just one line of code:  @DateTime.Now
29 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.
30 How can you do authentication and authorization in MVC? You can use Windows or Forms authentication for MVC.
31 How to implement Windows authentication for MVC? <authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization> 
32 How do you implement Forms authentication in MVC?
Step 1:

<authentication mode="Forms">
<forms loginUrl="~/Home/Login"  timeout="2880"/>
</authentication>

Step 2:
public ActionResult Login()
{
    if ((Request.Form["txtUserName"] == "Shiv") &&
          (Request.Form["txtPassword"] == "Shiv@123"))
    {
        FormsAuthentication.SetAuthCookie("Shiv",true);
        return View("About");
    }
    else
    {
        return View("Index");
    }
}

Step 3:
[Authorize]
PublicActionResult Default()
{
    return View();
}
[Authorize]
publicActionResult About()
{
     return View();
33 How to implement AJAX in MVC
34 What kind of events can be tracked in AJAX?
35 What is the difference between ActionResult and ViewResult? ActionResult is an abstract class while ViewResult derives from the ActionResult class public ActionResult DynamicView()
{
   if (IsHtmlView)
     return View(); // returns simple ViewResult
   else
     return Json(); // returns JsonResult view
36 What are the different types of results in MVC? 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:

ViewResult - Renders a specified view to the response stream
PartialViewResult - Renders a specified partial view to the response stream
EmptyResult - An empty response is returned
RedirectResult - Performs an HTTP redirection to a specified URL
RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
JsonResult - Serializes a given ViewData object to JSON format
JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
ContentResult - Writes content to the response stream without requiring a view
FileContentResult - Returns a file to the client
FileStreamResult - Returns a file to the client, which is provided by a Stream
FilePathResult - Returns a file to the client
37 What are ActionFilters in MVC?
38 What are the different types of action filters? 1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters
39 If we have multiple filters, what’s the sequence for execution? 1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters
40 Can we create our own custom view engine using MVC? Yes
Step 1: We need to create a class which implements the IView interface. In this class we should write the logic of how the view will be rendered in the render function.
Step 2: We need to create a class which inherits from VirtualPathProviderViewEngine and in this class we need to provide the folder path and the extension of the view name. For instance, for Razor the extension is “cshtml”; for aspx, the view extension is “.aspx”, so in the same way for our custom view, we need to provide an extension.
Step 3: We need to register the view in the custom view collection. The best place to register the custom view engine in the ViewEngines collection is the global.asax file
41 How to send result back in JSON format in MVC JsonResult class public JsonResult getCustomer()
{
    Customer obj = new Customer();
    obj.CustomerCode = "1001";
    obj.CustomerName = "Shiv";
    return Json(obj,JsonRequestBehavior.AllowGet);
}
42 What is WebAPI? WebAPI is the technology by which you can expose data over HTTP following REST principles
43 But WCF SOAP also does the same thing, so how does WebAPI differ?
44 With WCF you can implement REST, so why WebAPI? WCF was brought into implement SOA, the intention was never to implement REST. WebAPI is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating REST service, WebAPI is more preferred. public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }
    // POST api/values
    public void Post([FromBody]string value)
    {
    }
    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {
    }
    // DELETE api/values/5
    public void Delete(int id)
    {
    }
45 How can we detect that a MVC controller is called by POST or GET? Request.HttpMethod property public ActionResult SomeAction()
{
    if (Request.HttpMethod == "POST")
    {
        return View("SomePage");
    }
    else
    {
        return View("SomeOtherPage");
    }
}
46 What is Bundling and Minification in MVC? Bundling and minification helps us improve request load times of a page thus increasing performance.
47 How does bundling increase performance? Web projects always need CSS and script files. Bundling helps us combine multiple JavaScript and CSS files in to a single entity thus minimizing multiple requests in to a single request

Can be checked via fiddler or developer tool
48 How do we implement bundling in MVC? public  class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
           "~/Scripts/*.js"));
        BundleTable.EnableOptimizations = true;
    }
}

<%= Scripts.Render("~/Scripts/MyScripts")  %>
49 How can you test bundling in debug mode? BundleTable.EnableOptimizations = true;
50 Explain minification and how to implement it Minification reduces the size of script and CSS files by removing blank spaces , comments etc.  // This is test
var x = 0;
x = x + 1;
x = x * 2;

var x=0;x=x+1;x=x*2;
51 How do we implement minification? steps to implement bundling and minification are the same.
52 Explain Areas in MVC? Areas help you to group functionalities in to independent modules thus making your project more organized
53 Explain the concept of View Model in MVC? A view model is a simple class which represents data to be displayed on the view.
54 What kind of logic view model class will have?
55 How can we use two ( multiple) models with a single view?
56 Explain the need of display mode in MVC?
57 Explain MVC model binders? Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model
58 Explain the concept of MVC Scaffolding? Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. 
59 What does scaffolding use internally to connect to database? It uses Entity framework internally
60 How can we do exception handling in MVC?
61 How can you handle multiple Submit buttons pointing to multiple actions in a single MVC view?
62 What is CSRF attack and how can we prevent the same in MVC?

No comments:

Post a Comment