Translate

Important .Net MVC question for Experience 5 to 8 years

My title
Please go through the Dot Net Interview questions for the experienced professionals having 5 to 8 years of experience.

Usually, Interviewer would start from your current project asking you to explain your current project and the technologies used in the project.

Please make sure you update your resume such that you specify the technology that you thoroughly have worked on or revised before the interview.

Please go through the interview question below:

.Net MVC Questions

1. What is DotNet MVC? Explain Lifecycle of MVC? 

Ans : 
MVC stands for Model View Controller.

Model: Model consists of the details related to entity which needs to pass in
between View and the Controller.

View: View represents the layout of the page.

Controller: Controller handles the request from the user, redirects the request to the desired action and returns the result.

Life Cycle of MVC;
Any web application has two phases one is Request and other is response

1) User requests the page URL.

2) On fresh Request, Route.config is filled in global.asax file and the route collection is created to fill route table. It consists of all the routes required in the application.

3) Depending on the URL requested the URL routing module determines Route object which contains which route will invoke which action method this helps in creating the Request Context object.

4) Request Object is sent to the MVC handler which in turn executes the Execute method for the current Request.

5) Once the Execute method is fired desired Action method is called using ControllerActionInvoker according to the Rout Object definition.

6) Once the Action is called the Business Logic is processed and the results are returned in the form of JSONResult, FileResult or ViewResult.

is the RouteConfig used for? Can unwanted route be excluded from RouteConfig, if yes then how the route can be excluded?

Ans: RouteConfig class holds the Default route that used in the application. Developer can also 
define other custom routes in the RouteConfig class



protected void Application_Start()
{
          RouteConfig.RegisterRoutes(RouteTable.Routes);
}
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new 
            { 
                controller = "Home", 
                action = "Index", 
                id = UrlParameter.Optional
            }
        );
    }
}


3) What is Controller in MVC?

Ans: Controller process the incoming requests, handle user input and interactions and execute appropriate execution logic.

As seen in the example below Controller is suffixed with the nameController in the End, Note it is important to End the Controller with the suffix "Controller" such that the MVC recognizes the method as the Controller Eg: HomeController, InventoryController etc.
  
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}


4) What is Model in MVC?
Ans: Model object represents the part of the application that handles the domain logic or the business logic, Model handles the data that is passed from View to the Controller or from Controller to view. The Model carries the value of the Entity(Class) that needs to be communicated between the View and the Controller.

Example:- 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcSimpleModelBinding.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public int Zipcode { get; set; }
    }
}

4) Explain what are views in MVC and different View that you have used in MVC?
Ans: View represents the presentation layer for the Applications. View renders the UI for that data 
that is passed by the Controller Action to the View.

The view should not contain business logic or database logic, it should be purely used for the UI representation of the Entity.

There are different types of View
1) View Page
2) Partial View
3) Shared View or Master Page View

1) View Page 

This is inherited from View page BaseClass to create a normal view page in MVC application. 
View page can be created using.

There are two different types of view strongly typed view and Dynamic View.
a) Strongly Typed View:

1) In Strongly typed view, Model gets passed into the view.
2) Any changes made to the model, View will get refreshed automatically with the new changes.
3) Benefits of Strongly Typed view is your we will be strongly Typed with a particular Model.

@model StudenModel 
@{
    ViewBag.Title = "Student";
    Layout = "~/Views/Shared/_StudentHome.cshtml";
}


b) Dynamic View:
1) Dynamic view is the view created using the Dynamic object.
In the Dynamic view, the Type(Class) is not predefined in the application.

@model Dynamic
@{
    ViewBag.Title = "Student";
    Layout = "~/Views/Shared/_StudentHome.cshtml";
}

ViewBag is a dynamic type, if  ViewBag is used as a property holder in the View, then that View act as Dynamic View.

2) Partial View 

A Partial View is a view which gets loaded into another view, this view can be loaded into any calling view as a part of that view.

Partial view works as UserControl used to work in Asp.Net Web Forms. It prevents rewriting of a UI component that needs to be used within the multiple Views.

Example:-


@section Tabs
{
    @Html.Partial("~/Views/Waiver/_TabsMyHealth.cshtml")
}

In the above example, a Partial View _TabsHealth.cshtml is created in the mentioned path. This Partial View is called as a part of another view where the content of _TabsMyHealth.cshtml need
to be shown on the page.

In order to show the UI content of _TabsMyHealth.cshtml, a section/ placeholder @section Tabs is created in the calling View Page. Similarly, the Partial View page can be called in any other view which requires this section to be seen in that particular View.

3) Shared View or Master Page View 

Shared View is the View Page which acts as the MasterPage in the Asp.Net Web Forms. But it is quite different as compared to traditional MasterPage.

Shared View needs to be placed inside the Shared folder of the MVC folder structure so that it is available to all the Views.

Also, a section of code needs to included in the View page in order to associate the view with the 
required Master Page.

Find the code as follows:


@model Dynamic
@{
    ViewBag.Title = "Student";
    Layout = "~/Views/Shared/_StudentHome.cshtml";
}



5) Explain the Different types of Action Result in MVC?

Ans: Different types of Action Results are as follows

Action Result
Helper Method
Description
Renders a view as a Web page.
Renders a partial view, which defines a section of a view that can be rendered inside another view.
Redirects to another action method by using its URL.
Redirects to another action method.
Returns a user-defined content type.
Returns a serialized JSON object.
Returns a script that can be executed on the client.
Returns binary output to write to the response.
(None)
Represents a return value that is used if the action method must return a null result (void).
6) What are Action Filters and what is the use of Action Filter?
Ans:  An Action filter is an attribute that can be applied above the entire controller or on top of the particular Action method.
The ASP.NET MVC framework includes several action filters:
  • OutputCache – This action filter caches the output of a controller action for a specified amount of time.
  • HandleError – This action filter handles errors raised when a controller action executes.
  • Authorize – This action filter enables you to restrict access to a particular user or role.

Example:

[LogActionFilter]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }
}

using System;
using System.Diagnostics;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1.ActionFilters
{
     public class LogActionFilter : ActionFilterAttribute

     {
          public override void OnActionExecuting(ActionExecutingContext filterContext)
          {
               Log("OnActionExecuting", filterContext.RouteData);       
          }

          public override void OnActionExecuted(ActionExecutedContext filterContext)
          {
               Log("OnActionExecuted", filterContext.RouteData);       
          }

          public override void OnResultExecuting(ResultExecutingContext filterContext)
          {
               Log("OnResultExecuting", filterContext.RouteData);       
          }

          public override void OnResultExecuted(ResultExecutedContext filterContext)
          {
               Log("OnResultExecuted", filterContext.RouteData);       
          }


          private void Log(string methodName, RouteData routeData)
          {
               var controllerName = routeData.Values["controller"];
               var actionName = routeData.Values["action"];
               var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
               Debug.WriteLine(message, "Action Filter Log");
          }

     }
}



7) What is the order in which ActionFilters get Executed?

Ans: The order in which the filters are executed are as follows

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

All the above filters have OnExecuting and OnExecuted method which can be used to handle certain events based on the filter types.

Example:

OnActionExecuting()
OnActionExecuted()
OnResultExecuting()

For the details you can refer the below link:
https://msdn.microsoft.com/en-us/library/gg416513(VS.98).aspx

8) What is NoAction filter and where can it be used?
Ans: This is the action filter attribute, used to indicate this method of the controller is not an Action method.


[NonAction]
public ActionResult About()
{
 ViewBag.Message = "Your application description page.";
 return View();
}
  •