MVC Interview Question and Answers with Example - Part 2


Below is top 100 MVC interview question and answers with examples for freshers and intermediate developers.

What is Area?

Area allows us to partition large application into smaller units where each unit contains separate MVC folder structure, same as default MVC folder structure. Area was introduced in ASP.NET MVC2.

  • Creating area
  • Registering area

How to register Area?

Register area in Application_Start event in Global.asax.cs as below.
AreaRegistration.RegisterAllAreas();
Always remember the order of registering the Areas must be on top, so that all of the settings, filters and routes registered for the applications will also apply on the Areas.

What is Filter?

When you want to execute some logic before or after an action method executes, you can use filters for this purpose. Filters can be applied to an action method or controller in a declarative or programmatic way.
Declarative means by applying a filter attribute to an action method or controller class and programmatic means by implementing a corresponding interface or class.

What are the different types of Filters?

Below table shows the filter types, built-in filters for the type and interface which must be implemented to create a custom filter class.

Filter TypeDescriptionBuilt-in FilterInterface
Authorization filters Performs authentication and authorizes before executing action method. [Authorize], [RequireHttps] IAuthorizationFilter
Action filters Performs some operation before and after an action method executes. IActionFilter
Result filters Performs some operation before or after the execution of view result. [OutputCache] IResultFilter
Exception filters Performs some operation if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. [HandleError] IExceptionFilter

What is the order of execution of filters?

  • Authorization filters
  • Authorization filters
  • Result filters

Exception filters will be executed when any exception occurs irrespective of order.

How to register or configure filter in ASP.NET MVC?

You can configure filter at 3 level as shown below.

At Global level:
You can apply filters at global level in the Application_Start event of Global.asax.cs file by using default FilterConfig.RegisterGlobalFilters() method.
Global filters will be applied to all the controller and action methods of an application.

Ex. Registering in-built exception filter.

// MvcApplication class contains in Global.asax.cs file 
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }
}

// FilterConfig.cs located in App_Start folder 
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());  // for handling exception using inbuilt method
    }
}

At Controller level:
Filters can also be applied to the controller class. So, filters will be applicable to all the action method of Controller class if it is applied to a controller class.

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

At Action level:
You can apply filters to an individual action method also. So, filter will be applicable to that particular action method only.

public class HomeController : Controller
{
    [HandleError]
    public ActionResult Index()
    {
        return View();
    }
}

What is exception filter in MVC?

An exception filter executes when there is an unhandled exception occurs in your application.
HandleErrorAttribute ([HandlerError]) class is a built-in exception filter class in MVC framework.
This built-in HandleErrorAttribute class renders Error.cshtml included in the Shared folder by default, when an unhandled exception occurs.
Please make sure that CustomError mode is on in System.web section of web.config, in order for HandleErrorAttribute work properly. <customerrors mode="On" />

How to create Custom Exception filter or override exception filter?

Step 1: Creating custom exception filter
There are 2 ways to create custom exception filters.
1) By inheriting FilterAttribute, IExceptionFilter or
2) By inheriting HandleErrorAttribute as shown below.

class MyErrorHandler : FilterAttribute, IExceptionFilter
{
public override void IExceptionFilter.OnException(ExceptionContext filterContext)
    {
        LogToMethod(filterContext.Exception); // log your exception here
        base.OnException(filterContext);
    }
}

OR

class MyErrorHandler : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        LogToMethod(filterContext.Exception);
        base.OnException(filterContext);
    }
}

Step 2: Applying filters at Global or Controller or Action level.

What is OutputCache filter attribute?

OutputCache is a built-in action filter attribute that can be apply to an action method for which we want to cache the output. For example, output of the following action method will be cached for 100 seconds.

[OutputCache(Duration=100)]
public ActionResult Index()
{
    return View();
}

How to create Custom Action Filter in MVC?

You can create custom action filter by two ways as shown below
1) By inheriting IActionFilter interface and FilterAttribute class or
2) By inheriting ActionFilterAttribute abstract class as shown below.

IActionFilter interface include following methods to implement:

  • void OnActionExecuted(ActionExecutedContext filterContext)
  • void OnActionExecuting(ActionExecutingContext filterContext)
ActionFilterAttribute abstract class includes the following methods to override:
  • void OnActionExecuted(ActionExecutedContext filterContext)
  • void OnActionExecuting(ActionExecutingContext filterContext)
  • void OnResultExecuted(ResultExecutedContext filterContext)
  • void OnResultExecuting(ResultExecutingContext filterContext)

1) Creating Custom Filter.

public class TestLogAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        LogData("OnActionExecuted", filterContext.RouteData); 
    }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        LogData("OnActionExecuting", filterContext.RouteData);      
    }
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        LogData("OnResultExecuted", filterContext.RouteData);      
    }
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        LogData("OnResultExecuting ", filterContext.RouteData);      
    }
    private void LogData(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);
    }
}

2) Applying TestLog ActionFilter to Controller.

[TestLog]
public class StudentController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

What are html helpers?

HtmlHelper class generates html elements using the model class object in razor view. It binds the model object to html elements to display value of model properties into html elements and also assigns the value of the html elements to the model properties while submitting web form.
@html.actionlink
html: is property of type htmlhelper in base class and actionlink: is extension method

What are the types of html helpers?

Below are the 3 types of html helpers.

  • 1) Inline html helpers
  • 2) Built-in Html Helpers
    1.   Standard html helper
    2.   Strongly typed html helper
    3.   Templated html helper
  • 3) Custom html helper

How to create Inline html helper in ASP.NET MVC?

Inline html helper is created in the same view by using the Razor @helper tag. These helpers can be reused only on the same view.

@helper ListOfCountry(string[] country)
{ 
    <ol>
        @foreach (string c in country)
        {
            <li>@c</li> 
        }
    </ol>
}
@ListOfCountry(new string[] { "India", "USA", "UK" })

What are the built-in html helpers?

Built-In Html Helpers are extension methods on the HtmlHelper class. The Built-In Html helpers can be divided into 3 categories.

1) Standard Html Helpers: These helpers are used to render the most common types of HTML elements like as HTML text boxes, checkboxes etc.
TextBox @Html.TextBox("txtName", "Rahul")
Output:

<input id="txtName" name="txtName" type="text" value="Rahul" />

2) Strongly typed html Helpers: These helpers are used to render the most common types of HTML elements in strongly typed view like as HTML text boxes, checkboxes etc. The HTML elements are created based on model properties..
TextBox @Html.TextBoxFor(x => x.Name)
Output:

<input id="Name" name="Name" type="text" value="val from model" />

3) Templated html helpers: These helpers figure out what HTML elements are required to render based on properties of your model class. This is a very flexible approach for displaying data to the user, although it requires some initial care and attention to set up. To setup proper HTML element with Templated HTML Helper, make use of DataType attribute of DataAnnitation class.
For example, when you use DataType as Password, A templated helper automatically render Password type HTML input element.

Templated HelperExample
DisplayRenders a read-only view of the specified model property and selects an appropriate HTML element based on property’s data type and metadata.
Html.Display("Name")
DisplayForStrongly typed version of the previous helper.
Html.DisplayFor(m => m. Name)
EditorRenders an editor for the specified model property and selects an appropriate HTML element based on property’s data type and metadata.
Html.Editor("Name")
EditorForStrongly typed version of the previous helper.
Html.EditorFor(m => m. Name)

How to create Custom html helpers?

Custom html helpers: You can create your own custom helper methods by creating an extension method on the HtmlHelper class or by creating static methods with in a utility class.

public static class CustomHelpers
{
    public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText)
    {
        string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";
        return new MvcHtmlString(str);
    }

    //Readonly Strongly-Typed TextBox Helper 
    public static MvcHtmlString TextBoxFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, bool isReadonly)
    {
        MvcHtmlString html = default(MvcHtmlString); if (isReadonly)
        {
            html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, new { @class = "readOnly", @readonly = "read-only" });
        }
        else
        {
            html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression);
        }
        return html;
    }
}

What is difference between Html.TextboxFor and Html.EditorFor?

TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control.
EditorFor: This control is bit smart. It renders HTML markup based on the datatype of the property. E.g. suppose there is a boolean property in model. To render this property in the view as a checkbox either we can use CheckBoxFor or EditorFor. Both will be generate the same markup.

What is difference between TextBox and TextBoxFor?

  • @Html.TextBox() is loosely typed method whereas @Html.TextBoxFor() is a strongly typed (generic) extension method.
  • TextBox() requires property name as string parameter where as TextBoxFor() requires lambda expression as a parameter.
  • TextBox doesn't give you compile time error if you have specified wrong property name. It will throw run time exception.
  • TextBoxFor is generic method so it will give you compile time error if you have specified wrong property name or property name changes. (Provided view is not compile at run time. )

What is Partial View?

Partial view is a reusable view, which can be used as a child view in multiple other views.
It is best practice to create partial view in the shared folder and partial view name is preceded by "_", but it is not mandatory. The "_" before view name specify that it is a reusable component i.e. partial view.

What are the ways to render Partial View?

@html.Partial: It accept partial view name as a string parameter and returns MvcHtmlString. It returns html string so you have a chance of modifing the html before rendering.
@Html.Partial("_Menu")
@html.RenderPartial: It returns void and writes resulted html of a specified partial view into a http response stream directly.
@Html.Partial("_Menu")
@html.Action: The RenderAction helper method invokes a specified controller and action and renders and returns partial view result as MvcHtmlString. The specified Action method should return PartialViewResult using the Partial() method.
@Html.Action("Index","Home")
@html.RenderAction: The RenderAction helper method invokes a specified controller and action and directly writes partial view result into HTTP response object.
@Html.RenderAction("Index","Home")

What is Layout View?

An application may contain common parts in the UI which remains the same throughout the application such as the logo, header, left navigation bar, right bar or footer section. ASP.NET MVC introduced a Layout view which contains these common UI parts, so that we don't have to write the same code in every page. The layout view is same as the master page of the ASP.NET webform application.
The razor layout view has same extension as other views, .cshtml or .vbhtml. Layout views are shared with multiple views, so it must be stored in the Shared folder.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

What are the different Rendering methods of Layout View?

Different rendering methods are:

  • RenderBody()
  • RenderSection(string)
  • RenderPage(string)

What does RenderBody method do?

RenderBody method exists in the Layout page to render child page/view. It is just like the ContentPlaceHolder on master page. A layout page can have only one RenderBody method.

What does RenderSection method do?

RenderSection method renders the content of a view which is wrapped in named section.
RenderSection can be configured as required or optional. If required, then all the child views must included that named section. By default, sections are mandatory.
There can be any numbers of RenderSection methods, and also not necessary to have RenderSection method.

In _Layout.cshtml

<body> 
@RenderBody() 
@RenderSection("myDataSection",false) 
</body>

In Index.cshtml

@section myDataSection
{
    <div>My data</div>
}

What does RenderPage method do?

RenderPage method exists in the Layout page to render other page exists in your application. A layout page can have multiple RenderPage method.
In _Layout.cshtml page
@RenderPage("~/Views/Shared/_Menubar.cshtml")

What is difference between RenderBody and RenderSection in ASP.NET MVC?

RenderBody()RenderSection()
RenderBody must be present in the layout view.RenderSection method is optional.
RenderBody renders all the content of child view which is not wrapped in named section.RenderSection renders only a part child view that is wrapped under named section.
Multiple RenderBody() method is NOT allowed in a single layout view.Multiple RenderSection() method is allowed in a single layout view.
RenderBody() method does not include any parameter.RenderSection() method includes boolean parameter "required" which makes the section optional or mandatory. If required parameter is true then the child view must contain the section.

What is _ViewStart.cshtml page?

1) _ViewStart.cshtml page is use to set the layout view for many views. Code written in Layout view will be executed first.
2) _ViewStart.cshtml is included in the Views folder by default. It sets up the default layout page for all the views in the folder and its subfolders using the Layout property. You can assign a valid path of any Layout page to the Layout property as shown below.
@{ Layout = "~/Views/Shared/Layout.cshtml"; }
3) _ViewStart.cshtml can also be included in sub folder of View folder to set the default layout page for all the views included in that particular subfolder only.

What are the different ways to set layout page?

We can set layout view in different ways as shown below.
1) Set layout view in _Viewstart.cshtml page which is present into root directory of Views folder.
In _Viewstart.cshtml page which is present at root of Views Folder:

@{
layout = "~/Views/Shared/_Layout.cshtml";
}
2) Creating _Viewstart.cshtml page in individual Views folder seperately and set layout page.
3) Setting layout view path inside individual Views on top of view.
4) In Controller action method.
public ActionResult Index() 
{
return View("Index", "_Layout", model); 
}

What is bundling and minification?

Bundling and minification is used to improve the load time.
Bundling: Bundling allow us to load the bunch of static files from the server into one http request.
Minification: Minification technique optimizes script or css file size by removing unnecessary white space and comments and shortening variable names to one character.

What is Styles.Render and Scripts.Render?

Styles.Render: Style.Render is used to render a bundle of CSS files defined within BundleConfig.cs files. Styles.Render create style tag(s) for the CSS bundle.
Scripts.Render: Scripts.Render is also used to render a bundle of Script files by rendering script tag(s) for the Script bundle.

public class BundleConfig 
{ 
public static void RegisterBundles(BundleCollection bundles)
  {
    bundles.Add(new ScriptBundle("~/bundles/jquery")
               .Include( "~/Scripts/jquery-{version}.js"));
                bundles.Add(new StyleBundle("~/bundles/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"
                                                ));
  }
}

Using style bundle and script bundle View: You can use style and script bundle as shown below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Scripts.Render("~/bundles/jquery")
    @Styles.Render("~/bundles/css")
</head>
<body>
    
</body>
</html>

What is difference between ViewData, ViewBag and TempData?

ViewData and ViewBag are use to pass data from controller to view and TempData is use to pass data from controller to controller.

ViewData

  • ViewData is a dictionary object that is derived from ViewDataDictionary class.
  • ViewData is used to pass data from controller to corresponding view.
  • Its life lies only during the current request.
  • If redirection occurs then its value becomes null.
  • It's required typecasting for getting data and check for null values to avoid error.

ViewBag

  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
  • It's life also lies only during the current request.
  • If redirection occurs then its value becomes null.
  • It doesn't required typecasting for getting data.

TempData

  • TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
  • TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
  • Its life is very short and lies only till the target view is fully loaded.
  • It's required typecasting for getting data and check for null values to avoid error.
  • It's used to store only one time messages like error messages, validation messages.

What is TempData.Keep and TempData.Peek?

As TempData is used to pass data from one controller to other controller. So, TempData value gets lost after reading tempdata in second controller and it is not available in third controller i.e for the third request.
To persist tempdata values, we can use TempData.Peek and TempData.Keep method.

TempData.Keep

We can use TempData.Keep() method to persit all the TempData variables value or we can use overload version TempData.Keep(key) to persists specific tempdata values.

public ActionResult Index1()
{
    TempData["Data1"] = "Hello1";
    TempData["Data2"] = "Hello2";
    return View();
}
public ActionResult Index2()
{
   string Data1 = TempData["Data1"] as string; // TempData values will not be available in third request (i.e in Index3)
   string Data2 = TempData["Data2"] as string; // as it is marked for deletion

   TempData.Keep(); // TempData.Keep() will persist all values i.e Data1 and Data2 for third request.
   TempData.Keep("Data1");  // TempData.Keep("Data1") will persist only Data1 value.
   return View();
}

TempData.Peek

public ActionResult Index1()
{
    TempData["Data1"] = "Hello1";
    TempData["Data2"] = "Hello2";
    return View();
}
public ActionResult Index2()
{
    string Data1 = TempData.Peek("Data1") as string; // TempData.Peek() will persist only Data1 value.
    string Data2 = TempData.Peek("Data2") as string; // TempData.Peek() will persist only Data2 value.
    return View();
}

Page 2 of 3