MVC Interview Questions and Answers

1. How to send html string to controller in
Ans. If we put "validationinput" attribute on action method, it will allow html string.
 Exampe :

    public ActionResult ActionName(string data)

2. Can we define NonAction Method in
Ans. With the help of "NonAction" attribute we can define non action methods in controller.
Example : 

private void ShowMessage()

3. What does MVC segments include?
Ans. Controller, Actions and Parameters.

4. Is it possible to add class files without namespace in
Ans. Yes, we can add classes without namespace. But if you add next time with same class name it give you an error saying, Here Ia am trying to add class1 to the project, but next time when we try to add with same name the following  error is thrown.

 * * Error : The namespace '<global namespace>' already contains a definition for 'Class1'

 5. How to clear the form after post request is fired in
 Ans. We can clear the form fields by using,ModelState.Clear() at server side.Other option is by using, ModelState.Remove("Key") provided if key is known prior.

6. What is the html extension method to render partial view in
Ans. Html.Partial method

7. How to check whether section is defined in layout or not in
Ans. "IsSectionDefined" helper method is used to check whether section is defined in referencing views.

8. In which file default view is assigned to all the views in
Ans. In "_ViewStart.cshtml" file layout is assinged.
Example :

 Layout = "~/Views/Shared/_Layout.cshtml"; //on commenting this line you will not see layout to views

9. What is the default flag for RenderSection() in
Ans. By default it is "true". Means it expects definition for section.

10. Are @RenderBody() and @RenderSection() mandatory in
Ans. @RenderBody() is mandatory one where as @RenderSection() is optional.


11. How to disable the textbox using bootstrap in
Ans. We can disable the textbox in using bootstrap like following,

@Html.TextBoxFor(model => model.Name, new   {
                                            placeholder = "Readonly Field",
                                            @class = "form-control",
                                            @disabled = "true" 

12. How to include directory in bundle config file in
Ans. We can include directories in bundle config file like this,

bundles.Add(new ScriptBundle("~/bundles/Angular")
    .IncludeDirectory("~/Scripts/Controllers", "*.js")

13. Can View contains more than one form in
Ans. Yes, View can contain multiple forms.

14. Will the URL in points to physical location or not?
Ans. No, it will point to actions in controller.

15. How to change the default routing in
Ans. Under "App_Start" folder there is "RouteConfig.cs" file. In that file we can specify our action and controller name.

16. What happens when we try to send text box value on post request which is declared as follows

@Html.TextBoxFor(model => model.EmployeeId, new
                         placeholder = "EmployeeId",
                         @class = "form-control",
                         disabled = "true"

Ans. Here, the post request will send null value. Disabled fields never sends values.

17. How to make @html.TextBoxFor readonly in

Ans. We can use the "readonly" attribute like this 

@Html.TextBoxFor(model => model.EmployeeId, new
                                                placeholder = "EmployeeId",
                                                @class = "form-control",
                                                @readonly = "readonly"     

Readonly fields will send values on post request.

18. How to maintain TempData state in subsequent request in

Ans. There are 2 ways to achieve this,

     1. TempData.Keep("key");
     2. TempData.Peek("key").ToString();

19. How to clear form fields in

Ans. ModelState.Clear() will clear all the fields on page.

20. How to add errors in controllers in

Ans. Yes we can add errors in controllers by using, the "AddModelError" function.


ModelState.AddModelError("FirstName", "Sample error message");


21. What is the default url routing pattern in
Ans. The default url pattern is "Controller/Action/Parameters"

22. Which assembly is required for WebGrid in
Ans. System.Web.Helpers assembly is requried.

23. How to give "Post" method to form in views?
Ans. We can give httpmethod as post in view like the following,

@using (Html.BeginForm("CreateItem", "Inventory", FormMethod.Post))

24.How to select top records from table in using entity framework?
Ans. There is way to select top 'n' records from entity table like the following example,

25. How routes are evaluated in RouteConfig file?
Ans. Generally, routes are evaluated from top to bottom.

26. How to enable attribute routing in
Ans. First define routing on action method and adding the following line to RouteConfig file.

    public ActionResult FetchCustomers()
 public static void RegisterRoutes(RouteCollection routes)
        // Ignore Route definition here

        routes.MapMvcAttributeRoutes();  //  Here this line is very important for attribute routing
                                                                 //  Always use above routes.MapRoute();

        // Map Route definition here         


27. What happens when we not send parameters via url in
A. Example
    Target Url
    Url : "customer/getcustomer"
    Actual action :

    public ActionResult FetchCustomers(int id)

Ans. An error occurs here as there is no parameter passed and it is required.

28. How to set optional parameters in route attribute for an action in

Ans. Route attribute can be declared for an action with optional parameters by using "?" character.

    public ActionResult FetchCustomers(int? id)

  If you are not using route attribute, simpley use the following way.

 public ActionResult FetchCustomers(int? id) 

29. How to enforce route constraints in

Ans. We can put constraints on route attribute parameters. Simply we need to place constraint name after the parameter name separated by colon(":").


This is will enforce the parameter type should be integer.We can also use other constraints like,id:bool, id:max, id:min, id:range, etc.,

30. How to handle errors raised by all the action methods inside a controller in

Ans. First we need to set custom error mode on in webconfig file.

     <customerrors mode="On" /> --> webconfig

Then, adding "HandleError attribute above controller class.

    public class MainController : Controller
        public ActionResult Create()
            return View();

31. How to handle errors raised by particular action methods inside a controller in

Ans. Same as above but including "HandleError" attribute on action methods.

    public class MainController : Controller
        public ActionResult Create()
            return View();

32. What is the sequence of registration in  "Application_Start()" function of  Global.asax file in

Ans. The order goes like this follows,

  1.         Areas Registration
  2.         Filters Registration
  3.         Routes Registration
  4.         Bundles Registration

33. What are customErrors mode types in webconfig

Ans. There are 3 modes, On, Off and RemoteOnly.

34. How to override common route prefix in

Ans. There is a possibility to override the route prefix by special operator called Tilde (~).


    public class InventoryController : Controller
        //Route: Manager/Index
        public ActionResult Create()
            ViewBag.Message = "Action with route prefix";
            return View();

        //Route: Manager/Edit
        public ActionResult Edit()
            ViewBag.Message = "Overriding the route prefix here";
            return View();

35. Can we set default action in controller? How to set in

Ans. Yes, we can set default action in controller.The following example show how to achieve it,

public class InventoryController : Controller
        //Route: Manager/Index
        public ActionResult Create(int id)
            ViewBag.Message = "Action with route prefix";
            return View();

36. How to pass default value to parameter using attribute routing in

Ans. Default value can be passed to parameter by intializing it.
Example :

public class InventoryController : Controller
        public ActionResult Create(int id)
            return View();

37. If we have two pages with same names but with extension .aspx and .cshtml in mvc, which page will be called first?

Ans. The order will be like this .ascx, .aspx and .cshtml

38. Can we have multiple layouts in mvc?

Ans. We can declare multiple layouts in mvc but only one is called at time.

39. Which attribute is used to allow html tags in mvc?

Ans. [AllowHtml] is the attribute used to accept html tags in mvc.

40. How to redirect from one actio to another in mvc?

Ans. RedirecToAction("ActionName") method is used.

41. What is the difference between strongly typed view and loosely typed view in mvc?

Ans. Strongly type view is bounded to "Action" and Loosely typed view is not bounded to any "Action".

42. How can we change controller name in mvc url?

Ans. We can use RoutePrefix concept to change the actual controller name in the url.

42. How to DataBind using Entity DataSource?
Ans. Entity Data Model is one of the ORM model available in .NET. Using this model also we can prepare frontend objects for backend tables. EDM is superior model over Linq to Sql.EDM is added in 3.5 service    pack.Using EDM, 
1. One can connect with different databases unlike “Linq to Sql” which  connect only with Sql server.
2. You can implement conceptual model with EDM.Which is again not possible with Linq to Sql. 

43. What is App_code folder?
Ans. “App_code” : This folder is meant for writing all code related especially .CS files and some other also. When developed all content in this folder is automatically converted to a .dll file.
.dll --> (Assembly)
.exe --> (executable)

44. At what level route table is generated in
Ans. Global.asax level

45. When will be the route table is created in
Ans. For the first request the route table is created after that every subsequent 
request is just looked for route match.

46. Using which function route collection is defined in
Ans. MapRoute function is route collection is defined.

47. Can a actio have two different routes in
Ans. Yes we can defined the multiple routes for an action but with different route key.

48. Which event is responsible for registering the route in
Ans. In global.asax, the Application Start event will register the routes.

49. What is the base class for all the controllers in
Ans. Controller 

50. How to render html text in server side code in
Ans. we can use "@:" or "<text></text>" to specify html text inside a server side code if you do not have any other html in there.

if (@Model.IsActive)

51. Difference between @hmlt.displayname and @html.displaytext in
Ans. The DisplayText is same as Model.PropertyName. It will not display any text.
i.e., Model.PropertyName = @Html.DisplayText('PropertyName')

The @Htm.DisplayName is used to display text.

52. In which verison of Razor was introduced?
Ans. MVC 3

53. What is the other name for MVC6?
Ans. ASP.NET vNext

54. How the html controls are rendered in views?
Ans. Html helpers are used to render the html contols.

55. Which object is created after find the route match in
Ans. RouteData object is created.

56. What does the RouteData object contains?
Ans. RouteData contains the target controller and action names.

57. To which part of the the request first hits?
Ans. Controller

58. Which handlers are responsible for redirecting the request to controller?
Ans. MVCHandlers

59. How does the actions of controller are executed once the request is handled by mvchandlers in
An instance of controller is created first and then it exectues the executable action.

60. Which of the following code is correct for assigning the model value in view page?

a. @Html.HiddenFor(model=>model.FirstName,new{ @value='fname'});

b. @Html.HiddenFor(model=>model.FirstName,new{ Value='fname'});

c. @Html.HiddenFor(model=>model.FirstName,new{ value='fname'});

d. @Html.HiddenFor(model=>model.FirstName,new{ @type='fname'});

Ans. b

61. Which assembly among the following is the MVC framework defined? 
1. System.Web.Mvc
2. System.Mvc.Web
3. System.Mvc
4. System.Data.Mvc

Ans. 1

62. Can we use webforms in mvc application?
Ans. Yes, we can use webforms in mvc application.

63. In which file the routing rules defined in an MVC application? 
Ans. In Global.asax , Application_Start event.

64. Which attribute is used to make an Action of a controller as non-action in mvc application?
Ans. By default all public methods of a controller class are treated as action methods. 
We can override this default behaviour by just decorating the public method with NonActionAttribute.

65. What is the order in which the filters get executed when we implement mulitple filters? 

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

66. What are the Authorization filters in an mvc application? 
Ans. 1. RequireHttpsAttribute 
        2. AuthorizeAttribute 

67. Can we bypass filter execution in mvc application? 
Ans. Yes 

68. How to print escape sequence character for @ symbol in razor syntax? 
Ans. Just using another (i.e., @@ ) symbol 

69. Which filter does OutputCacheAttribute class represents? 
Ans. The Result Filter 

70. What are the different types of action filters in mvc?
Ans. Mvc supports following action filters,
1.Authorization filters
2.Action filters
3.Result filters
4.Exception filters

71. Why bundling and minification used in MVC?
Ans. Bundling and minification improves request load times of a page 
therefore increases performance.

72. What is the sequence for execution of filters in mvc?
Ans. Following is the sequence of execution of filters in mvc,
1.Authorization filters
2.Action filters
3.Response filters
4.Exception filters

73. How scaffolding is implemented in mvc?
Ans. Scaffolding uses Entity framework internally.

74. How to bind model two-way to input text type in mvc?
Ans. Just give the property name for input tag name attribute and value to model.

Example : 

<input type="text" id="fname" value="@Model.FName" name="FName"/>

Here, name attribute is assigned to property name of the model.

75. How to ScaffoldColumn attribute in mvc?
Ans. [ScaffoldColumn(true)]

76. Compare data annotation in mvc example?

   public class StudentModel
        [StringLength(10,ErrorMessage="length validation",MinimumLength=2)]
        public string FName { get; set; }

        [Compare("FName", ErrorMessage = "Name Should Match")]
        public string LName { get; set; }

Only after first and last name matching, the validation is passed.

77. How can we create action filters in mvc?
Ans.We can create action filters by two ways:
1. Inline action filter.
2. Creating an ActionFilter attribute.

78. What is the namespace for Razor view engine?
Ans. The namespace for Razor Engine is "System.Web.Razor"

79. What is the namespace for Webform view engine?
Ans. The namespace for Webform Engine is "System.Web.Mvc.WebFormViewEngine"

80. What delimeters used for webform view engine?
Ans. Webform uses <% and %> delimiters

81. How to remove default view engine from mvc?
Ans. We can remove default view engine from mvc by doing following,

protected void Application_Start()
 //Remove All View Engine including Webform and Razor

82. Can we make Custom View Engine in mvc?
Ans. One can create own view engine by implementing IViewEngine interface or by inheriting 
VirtualPathProviderViewEngine abstract class.

83. Routing constraints are applied at which level in mvc?
Ans. Routing constraints are applied at "RouteConfig.cs" level.

84. By default sections are mandatory or optional in mvc?
Ans. By default, sections are mandatory. To make sections optional, just provides the second parameter value as false, which is a Boolean value. 


85. Which attribute is used to control the sessoin states in mvc?
Ans. SessionState attribute provides more control over the behavior of session-state by specifying the value of SessionStateBehavior enumeration as given below:
1. Default
2. Disabled
3. ReadOnly
4. Required


Recent Posts


Receive Quality Tutorials Straight in your Inbox by submitting your Email below:

Delivered by FeedBurner

Protected by Copyscape Duplicate Content Checker