Mostly asked MVC interview questions for experienced


  •        What is MVC?

Answer: You can say it’s a design pattern or framework or library.  For any answer you should have a concrete response as we can prove that MVC can be anyone of these [Design Pattern/Library/Framework].

  • .      Why we need MVC, why not only ASP.net?

Answer: Over net you will find the answers like Separation of Concern, Unit Test, TDD [Test driven development] etc.

My Sincere suggestion would be, first you say it is open source and you have lot of option to customize existing MVC components as per your project requirement [Like Custom HTML helper, Custom Validation, Custom Action Result etc.].

Another basic advantage is URL – which you can customize on your own.
For example: http://localhost:80/Employee/Details/5 instead of http://localhost:80/EmployeeDetails.aspx or hide the existing URL through attribute routing [MVC5].  URL works like a sitemap for end user which makes them feel happy.

Performance – as there is no ViewState for any control MVC is lightweight compare to asp.net.

If you have two separate teams (one for UI, another for dot net), both can works parallel without impacting others as there is no strongly coupled component. Like in ASP.net for ‘Button1’ you will have ‘Button1_Click ()’ event.

Compatibility or adaptability with different device and different browsers using multiple option of MVC like Display mode/ ViewPort of @media query, bootstrap etc.

Filters are too easy to work rather than httpHandler or httpmodule.

Support of all modern Plugin/tools like Telerik Kendo UI, Bootstrap, Knockout, angular, node etc.


  •    Can you write a code to have a custom validation?


Answer: Basically interviewer wants to know here whether you know the basic components to write a custom validation or not.
Those are ‘ValidationAttribute’, which you need to inherit/implement into your class and the method which you have to override is ‘IsValid’ which will have multiple overloaded options. If you want to get some another member inside Isvalid method you can use ValidationContext. Sample example you can find here. 1  2  3

  • .      How can you add validation over URL in MVC or how to have Routing constraints?

Answer: Please find the answer here.

  •   For example, inside an Action method in your controller, you will be returning like below. 

If(x == “MainWindow”)
return View(‘Test’,listEmployee);
else if (x==”PartialWindowForFilterData”)
return Json(listEmployee, JsonRequestBehavior.AllowGet);
else
return View();

The above statement is purely valid. Now, what will be the return type of this method ?

Answer : ActionResult. As ‘ActionResult’ is top of all other result type.

  •  How will you create a filter? ( Not specific to authentication/Authorization/Action/Exception).

Answer: Add a folder into your solution, Add a class , inherit ‘filterAttribute’  class into your class, add a entry into FilterConfig.cs inside App Start folder or Global.asax file.

  •         Now how make this filter as global? Or, without mentioning filterAttribute top of every  controllers or every action methods, get the functionality of filter attribute on top of  every controllers.

Answer: Make the same filter you created before as global. How? Inside FilterConfig or Application_Start() of Global.asax like below.
            GlobalFilters.Filters.Add(new MyActionFilterAttribute());
  •              How you create a custom HTML helper? How to make custom HTML helper accessible globally.

Answer: See this Video.


  •       Why we use area in MVC? How you communicate over areas?

Answer: Area got introduced in MVC 2.0. The basic purpose is to separate multiple different sets [controller-model-view] using a block/container called area based on the usability purpose.
For example: Admin may have a set of controller model and view which may not be related much with Normal end user. They can communicate through each other using multiple option like @HTML.ActionLink(“LinkName”, “Contrller”,”Action”,”area”,”htmlAttribute”)

  •       How to customize[Show, hide, segregate ] model properties ?

Answer: you have multiple options to do that.
i)                    Use ScafoldColumn to false to hide a property into view.
ii)                  Use Display(Name = “SomeDifferentName”)
 Over model class to display some different name.
iii)                Use ViewModel.
iv)                Use Bind class.
v)                  Use IModelBinder
Do google, you will get example and solution for each one of the above.


  • How request flow in MVC
Answer: See this Link and this


I will come with few more interview question for experienced in next.



You can follow this for a good reference written by my best mentor. 

Write a method which will take any numbers of input, any type of input and add values of all.


Below is the method which will accept any number of inputs and any type of inputs and add values of all.



Call this method inside yours Static void main like below with any number and any type of parameters.
Here outputs are,  a = 6 , b = abcXYZtest and c = 6.9.

MVC: Set Master Page File based on day and Night time

  
Here you need to follow just simple four steps to get this activity done.

Step1:

On your Controller set a “TempData” [a variable which is shared among controller and view internally using session] variable like below to identify current time is Day or Night.

     
   public ActionResult Index()
   {

      TimeSpan time = DateTime.Now.TimeOfDay;
      if ((time > new TimeSpan(05, 59, 00)) && (time < new TimeSpan(17, 59, 00)))
            {
                TempData["DayNight"] = true; //True is Day

            }
            else
            {
                TempData["DayNight"] = false; //False in Night
           
            }
     return View();
    }



I have added it on “Index” Action method on some controller. It is not mandatory to set it on only index, you can use any other action method but need to make sure that you once after executing action method you should return any view basically where[returning View] we will do our stuff for Master page file selection.

Step2:

Create your view by right clicking on Action method à Add View. Default name is Index. Press okay. So a new View called “Index” gets created on the view folder.

[This is step is pretty much common in MVC. We create controller named as Employee, on the Employee controller we have an action method named as Index, then we right click and add a view. On the View folder you have a subfolder Employee and within that one page “Index.aspx” (aspx engine) or “Index.cshtml”(for razor engine)]


Step3:

Now  add two views in your shared folder like below. They are named as “_DayLayout” and “_NightLayout”. Simple and straight forward.



Step4:

Now top of your main view [The View which you have created in Step2] include the below. I am using MVC3 with Razor view.


@{ 
    if (Convert.ToBoolean(@TempData["DayNight"]) == true)
    {
        Layout = "~/Views/Shared/_DayLayout.cshtml";
    }
    else
    {
        Layout = "~/Views/Shared/_NightLayout.cshtml";
    }   
}



You are done. Execute and Check it where as in ASP.Net we use to set up master page file in “Page_PreInit()  method . Feel free to post your query @nit.pradip@gmail.com


MVC: Multiple Models in One Single View

Here the question is say you have two model M1 and M2. M1 model consistd properties like a,b. M2 Consists properties like c,d. All a,b,c, d are required(Tagged as [Required]). Now you have a single View V. You have to display all a,b,c,d four properties into V view.

The simplest solution is first create M1 and M2 model class with a,b[in M1] and c,d[in M2] property . Now in M1 Model have a list property of M2 class

public List<M2> M2Prop { get; set; }

Access M1 Class in V view. You are done. Have a look on the below sample code.

public class Student
    {
        [Required]
        public int RollNo { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Class { get; set; }

        public string Address { get; set; }

        public List<StudentScore> StudentScore { get; set; }

   }

And the ‘StudentScore’ class is as follows.

public class StudentScore
    {
        [Required]
        public int StudentRollNo { get; set; }

        [Required]
        public string StudentName { get; set; }

        [Required]
        public string Subject { get; set; }

        [Required]
        public int Marks { get; set; }

        [Required]
        public string Grade { get; set; }

    }

Create View with strongly typed of Student Class.
And on the view it is like below.

@model IEnumerable<MultipleModelInOneView.Models.Student>


@foreach (var item in Model)
    {

<td>
                @item.RollNo
            </td>
            <td>
                @item.Name
            </td>

       @foreach (var score in item.StudentScore)
            {
                 <td>
                    @score.Grade
                  
                </td>
                <td>
                    @score.Marks
                </td>
           
            }

}



You are done. Feel free to post any query.

MVC: Hide a model property to display in view


Below is the model class for Employee. Pretty Simple!

public class Employee
    {
        [Required]
        public int EmpID { get; set; }

        [DisplayName("Name")]
        [Required]
        public string EmpName { get; set; }

        [DisplayName("Bussiness Segment")]
        [Required]
        public string EmpDept { get; set; }
       
        [Required]
        public string Salary { get; set; }

        [DisplayName("Designation")]
        [Required]
        public string EmpLevel { get; set; }
    }


And below is the view I have to display list of employees which I have created like in Index action method of Employee Controller – right click and add View and then select strongly type view and then select Employee model class.

@model   IEnumerable<MvcAppModelBinding.Models.Employee>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
</head>
<body>
    <fieldset>
        <legend>Employee</legend>
   
        @foreach (var item in Model)
        {
        <div class="display-label">EmpID</div>
        <div class="display-field">@item.EmpID</div>
   
        <div class="display-label">EmpName</div>
        <div class="display-field">@item.EmpName</div>
   
        <div class="display-label">EmpDept</div>
        <div class="display-field">@item.EmpDept</div>
   
        <div class="display-label">Salary</div>
        <div class="display-field">@item.Salary</div>
   
        <div class="display-label">EmpLevel</div>
        <div class="display-field">@item.EmpLevel</div>

       
        }

    </fieldset>
    <p>
        @Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
        @Html.ActionLink("Back to List", "Index")
    </p>
</body>
</html>

Now in the Employee Controller Index is the action method where I am display the above view.
The below code is in Employee Controller class.

// GET: /Employee/


// Static list to display multiple Employee records

 public static List<Employee> lstEmp = new List<Employee>();

        public ActionResult Index([Bind(Exclude = "EmpLevel")]Employee emp)
        {
            lstEmp.Add(emp);
            return View(lstEmp);
        }

The only new thing is Bind which applied on the class level. Like Exclude you also have include and prefix tag here. Here all the properties except designation/EmpLevel will be displayed. So I am hiding ‘EmpLevel’ property of Employee class model from controller.

Sort based on given order with no repeating code

static void Main(string[] args)
        {
           
            Console.WriteLine("Enter How many numbers you want for Sort:-");
            int arrLength = Convert.ToInt32(Console.ReadLine());

            int[] userInputs = new int[arrLength];
           

            Console.WriteLine("Enter List of  {0} Integer items to sort:" ,arrLength);
            for(int i=0;i<arrLength ; i ++)
            {
                userInputs[i] =Convert.ToInt32(Console.ReadLine());
            }
            Console.WriteLine("Enter whcih order you want to sort:");
            Console.WriteLine("\t Press '0' for Descending | \t '1' for Ascending:");
            int order = Convert.ToInt32(Console.ReadLine());
           
            userInputs = GetSortedData(userInputs, order);

            Console.WriteLine("The Sorted result is as below:");
            for (int num = 0; num < arrLength; num++)
            {
              Console.Write(" "+ userInputs[num]+" ");
            }
            Console.ReadLine();

        }



        /// <summary>
        /// This method sorts your input array on your specified order.
        /// </summary>
        /// <param name="inputArray"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public static int[] GetSortedData(int[] inputArray, int order)
        {
            for (int i = 0; i < inputArray.Length - 1; i++)
            {
                for (int j = 0; j < inputArray.Length - 1; j++)
                {
                    if (order == 0? inputArray[j] < inputArray[j + 1] : inputArray[j] > inputArray[j + 1])
                    {
                        int temp = inputArray[j];
                        inputArray[j] = inputArray[j + 1];
                        inputArray[j + 1] = temp;
                    }               
                }           
            }
            return inputArray;
        }