Skip to content

Frequently Asked Interview questions on MVC 

Here we provide Interview questions on MVC which will help you to crack your interview on MVC. This article will help you a lot, read this completely…

General Interview questions on MVC

What is MVC?

MVC(Model-View-Controller) is an architectural pattern that decouples components of a web application. It separates the representation and user interaction. It’s divided into three broader sections, Model, View, and Controller.

• Model: is a business entity and is used to represent the application domain data. The model represents the real-world object and provides data to the View.

• View is responsible for the look and feel. “View” is the user interface to render the domain data.

• Controller: translates user actions into appropriate operations performed on the model. The Controller is responsible for taking the end-user request and loading the appropriate Model and View. Request sent by the user always scatters through the controller and its responsibility is to redirect to the specific view.

• By using the MVC pattern, we can develop applications that are more flexible to changes without affecting the other components of our application.

• Microsoft has streamlined the development of MVC-based applications using the ASP.NET MVC Framework.

Routing Interview Questions on MVC

Routing Interview Questions on MVC

Routing Interview Questions on MVC

What do you mean by Routing in MVC?
Routing is a pattern matching mechanism of incoming requests to the URL patterns which are registered in the routing table.

• Routing helps you to define a URL structure and map the URL with the controller.

• Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses the “go” button, the routing engine uses routing rules that are defined in the Global.asax file in order to parse the URL and find out the path of the corresponding controller.

• For instance let’s say we want that when a user types “http://localhost/View/ViewEmployee/”, it goes to the Employee Controller and invokes the DisplayEmployee action.

• This is defined by adding an entry into the routes collection using the map route function.

• Below is the code that shows how the URL structure and mapping with controller and action are defined.

routes.MapRoute(
“View”, // Route name
“View/ViewCustomer/{id}”, // URL with parameters
new { controller = “Customer”,
action = “DisplayCustomer”,
id = UrlParameter.Optional }); // Parameter defaults

• Class – UrlRoutingModule is used for the same process.
Difference between ASP.Net and MVC routing?
• In the case of a typical ASP.NET application, incoming requests are mapped to physical files such as the .aspx file.

• On the other hand, the ASP.NET MVC framework uses friendly URLs that more easily describe user’s actions but are not mapped to physical files.

Let’s see below URLs for both ASP.NET and ASP.NET MVC.

//ASP.NET approach – Pointing to physical files (Application.aspx)
//Displaying all Applications
http://locahost:XXXX/applications.aspx

//Displaying a application by Id = 5
http://locahost:XXXX/application.aspx?Id=5

//ASP.NET MVC approach – Pointing to Controller i.e. Application
//Displaying all applications
http://locahost:XXXX/application

//Displaying application by Id = 5
http://locahost:XXXX/application/5/

What is Attribute Routing in MVC?
• Attribute routing uses attributes to define routes and it can be used on controller actions and even controller classes as well.

• ASP.NET Web API and MVC5 support this type of routing. In this type of routing, attributes are being used to define the routes.

• This type of routing gives more control over classic URI Routing. Attribute Routing can be defined at controller level or at Action level like –

• Action Level

public class HomeController: Controller
{

[Route(“Application/about”)] public ActionResult About()
{
ViewBag.Message = “You successfully reached Application/About route”;
return View();
}
}

 

• Controller Level

[RoutePrefix(“Application”)] public class HomeController : Controller
{

//Route: Application/Index
public ActionResult Index()
{
ViewBag.Message = “You are in Home Index”;
return View();
}

//Route: Application/About
public ActionResult About()
{
ViewBag.Message = “You successfully reached Application/About route”;
return View();
}
}

 

• Note: Remember that the conventional routing approach is not discarded, it’s still there and fully functional.

• Also, we can use both routing techniques in the same application.
How to enable Attribute Routing in MVC?
To enable attribute routing, call MapMvcAttributeRoutes() method in RegisterRoutes() method in RouteConfig class.

public class RouteConfig{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapMvcAttributeRoutes();
}
}

How to enable Attribute Routing in MVC?
To enable attribute routing, call MapMvcAttributeRoutes() method in RegisterRoutes() method in RouteConfig class.

public class RouteConfig{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapMvcAttributeRoutes();
}
}
Can we combine both Convention based and attribute based routing? if yes how ?
Yes, We can combine attribute routing with convention-based routing.

public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: “Default”
,url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home”
, action = “Index”
, id = UrlParameter.Optional
}
);
}

• Note: MapMvcAttributeRoutes() have to call before the Convention-based Routing.

Where is the route mapping code written?
How route table has been created in ASP.NET MVC?
The route mapping code is written in RouteConfig.cs file and registered using global.asax application starts the event.

RouteConfig.cs

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
}
);
}

global.asax

void Application_Start(object sender, EventArgs e) {
RegisterRoutes(RouteTable.Routes);
}

 

Can we map multiple URLs to the same action?
Yes, we can, we just need to make two entries with different key names and specify the same controller and action.

public class HomeController: Controller
{
[Route(“”Users/about””)] [Route(“”Users/aboutCompany””)] public ActionResult About()
{
return View();
}
}
Using this default route – {resource}.axd/{*pathInfo}, we can prevent the requests for the web resources files like – WebResource.axd or ScriptResource.axd from passing to a controller.

 

What are partial views in MVC?
A partial view is a reusable view (like a user control in traditional web forms) that can be embedded inside other views.

For example, let’s say for all pages of a site, we would like to reuse the left menu, header, and footer controls. So we can go and create partial views for each of these items and then we call that partial view in the main view.

Partial Views can be rendered in following ways –

• Html.Partial()
• Html.RenderPartial()

• For re-usability purposes partial views are used. Since it’s been shared with multiple views these are kept in a shared folder.

• When a partial view is instantiated, it gets its own copy of the ViewDataDictionary object that is available to the parent view. The partial view, therefore, has access to the data of the parent view.

• If the partial view updates the data, those updates affect only the partial view’s ViewData object. The parent view’s data is not changed.

Views Interview Questions on MVC

Interview questions on MVC 

Interview Questions on MVC

What is Layout in MVC?
Layout pages are similar to Master Pages in traditional web forms. This is used to set the common look across multiple pages.

On each child page we can write:
@{
Layout = “~/Views/Shared/CommonLayout.cshtml”;
}
This indicates child page uses the TestLayout page as its master page.

Explain Sections is MVC?
A section allows you to specify a region of content within a layout.

On Layout page we will use the below syntax for declaring a place holder –

@RenderSection(“TestSection”)

And in child pages we are defining these sections as shown below –

@section TestSection{
<h1>Test Content</h1>
}

• At runtime content from section TestSection will be placed at the position where @renderSection is defined on the Layout page.

• If any child page does not have this section defined then an error will be thrown so to avoid that we can render the HTML like this –

@RenderSection(“TestSection”, required: false)

• A view can define only those sections that are referred to in the layout page otherwise an exception will be thrown.

What is ViewStart Page in MVC?
• This page is used to make sure a common layout page will be used for multiple views.

• Code written in this file will be executed first when the application is being loaded.

• The _ViewStart.cshtml file will execute at the start of each view’s rendering. Any code contained within the code block in this file will execute before any code in the view. Typically, this file will set the layout template to be used by the views in the application:

@{
Layout = “~/Views/Shared/_Layout.cshtml”;
}

• An MVC application can have multiple _ViewStart.cshtml files.

• The order in which these files execute is dependent upon the location of the files in the folder hierarchy and the particular view being rendered.

• The MVC Runtime will first execute the code in the _ViewStart.cshtml file located in the root of the Views folder. It will then work its way up the folder hierarchy, executing the code in each _ViewStart.cshtml file it finds along the way.

For example:

If we have _ViewStart.cshtml files in the following locations:
1) View\_ViewStart.cshtml
2) View\Home\_ViewStart.cshtml
3) View\Products\_ViewStart.cshtml
and we render a view in the Views\Home folder, the MVC Runtime will first execute the code in file 1 and then execute the code in file 2. Since file 3 is not in the hierarchy of the Views\Home folder, the code in file 3 will not get executed.
[07:05, 20/07/2021] AA: Can you explain RenderBody and RenderPage in MVC?
[07:06, 20/07/2021] AA: • RenderBody method exists in the Layout page to render child page/view. It is just like the ContentPlaceHolder in master page in web forms. Views that use this layout page will get rendered at the place where @RenderBody() is written on the Layout page. That is the render body indicates where view templates that are based on this master layout file should fill in the body content.

@RenderBody()

• Layout page will have only one RenderBody() method.

• With the RenderPage, the content of the page can be filled by other pages. This takes the physical path of the file. RenderPage method also exists in the Layout page to render another page that exists in your application.

@RenderPage(“~/Views/Shared/_Header.cshtml”)
@RenderPage(“~/Views/Shared/_TopNav.cshtml”)

• A layout page can have multiple RenderPage methods.
[07:06, 20/07/2021] AA: Explain the methods used to render the views in MVC?
[07:06, 20/07/2021] AA: Below are the methods used to render the views from the action –

• View() – To return the view from action.

• PartialView() – To return the partial view from action.

• RedirectToAction() – To Redirect to different action which can be in same controller or in different controller.

• Redirect() – Similar to Response.Redirect() in webforms, used to redirect to specified URL.

• RedirectToRoute() – Redirect to action from the specified URL but the URL in the routing table has been matched.

Session Management Interview Questions on MVC

What is ViewData ?
ViewData contains the key, value pairs as dictionary and this is derived from class – ViewDataDictionary.

In the action method, we set the value for ViewData and in view, the value will be fetched by typecasting.

Controller

ViewData[“message”] = “This is a test message”;

AppInfo info = new AppInfo()
{
Name = 100,
ReleaseDate = new DateTime(2013, 01, 20),
Version = 1.0.1.100
};

ViewData[“appInfo”] = info;

View

@ViewData[“message”]

<h3>
@{
AppInfo info = (AppInfo)ViewData[“appInfo”];
@info.Name |
@info.ReleaseDate |
@info.Version
}
</h3>

• The controller can add key/values pairs to the view data. The data is then passed to the view when the view is rendered.

• The view can add to or change the data, which will be sent to the controller when the view is posted as part of a request.

• Data stored in the ViewData object exists only during the current request.

• In other words, as soon as the view is rendered in the browser the ViewData object is emptied.

What is ViewBag?
• ViewBag is a wrapper over ViewData and allows us to store and retrieve values using object-property syntax rather than key-value syntax used by dictionary objects.

• It does so using the dynamic data type feature of .NET.

• In addition to providing object-properties syntax ViewBag also saves you from the job of typecasting as you did with ViewData object.

Example:

Controller

ViewBag.message = “This is a test message”;

AppInfo info = new AppInfo()
{
Name = 100,
ReleaseDate = new DateTime(2013, 01, 20),
Version = 1.0.1.100
};

ViewBag.AppInfo = info;

View

@ViewBag.message

<h3>
@{
@ViewBag.AppInfo.Name |
@ViewBag.AppInfo.ReleaseDate |
@ViewBag.AppInfo.Version
}
</h3>
[07:07, 20/07/2021] AA: What is the difference between ViewBag and ViewData in MVC?
[07:07, 20/07/2021] AA: ViewBag is a wrapper around ViewData, which allows creating of dynamic properties.

The advantage of ViewBag over ViewData will be:

• In ViewBag no need to typecast the objects as in ViewData.

• ViewBag will take advantage of the dynamic keyword which is introduced in version 4.0.

• Before using ViewBag we have to keep in mind that ViewBag is slower than ViewData.

What is TempData?
• TempData in ASP.NET MVC is a dictionary object derived from TempDataDictionary.

• TempData stays for a subsequent HTTP Request as opposed to ViewBag and ViewData, those stay only for the current requests.

• This can also be used to store data while passing requests between two actions of the same controller or between different controllers.

//Controller Applications
public ActionResult GoToApp()
{
Applications applications= new Applications()
{
Name = “AppShells”,
Version = “1.0.0.1”
};
TempData[“applications”] = applications;
return RedirectToAction(“App”);
}

//Controller Class App
public ActionResult App()
{
Applications applications= TempData[“applications”] as Applications;
return View(Applications);
}

• Just like ViewData, typecasting and null checks are required for TempData also in order to avoid errors.

• Tempdata uses sessions to store data. So if you turn your session off for application, you will get an exception “The SessionStateTempDataProvider class requires session state to be enabled.”

• The value of TempData persists until it is read or until the current user’s session times out.

• TempData values are marked for deletion when you read them. At the end of the request, any marked values are deleted.
[07:08, 20/07/2021] AA: What are HTML helpers in MVC?
[07:08, 20/07/2021] AA: • HTML helpers help you to render HTML controls in the view.

• HTML Helpers are like controls in traditional web forms but Html Helpers are comparatively lightweight because these don’t have ViewState and event model as for ASP.NET Web Form Controls.

• From an implementation point of view, HtmlHelper basically is a method that returns a string that can be directly rendered to an HTML page.( i.e. an HTML string to render HTML tags).

For instance if you want to display a HTML textbox on the view , below is the HTML helper code.

@Html.TextBox(“strEmployeeName”) renders:<input id=”strEmployeeName” name=”strEmployeeName” type=”text” value=”” />

@Html.ActionLink(“AppShells Company Profile”, “CompanyInfo”) will render:<a href=”/Site/CompanyInfo”>AppShells Company Profile</a>

• For checkbox below is the HTML helper code.

<%= Html.CheckBox(“Employee”) %>

• Note: Custom HTML Helpers also can be created by overriding “HtmlHelper” class.

HTML Helpers Interview Questions on MVC

How can we navigate from one view to another using a hyperlink?
ActionLink of HTML helper can be used to navigate from one view to another.

The below code will create a simple URL that helps to navigate to the Home controller and invoke the About action.

@Html.ActionLink(“”About this Website””, “”About””)

The Html.ActionLink() helper above, outputs the following HTML:

<a href=””/Home/About””>About this Website</a>

The Html.ActionLink() helper has several properties:

• .linkText: The link text (label)
• .actionName: The target action
• .routeValues: The values passed to the action
• .controllerName: The target controller
• .htmlAttributes: The set of attributes to the link
• .protocol: The link protocol
• .hostname: The host name for the link
• .fragment: The anchor target for the link

What is the difference between action link and routing?
• ActionLink will generate the hyperlink tag to the specified controller action which uses the Routing API internally to generate URL.

@Html.ActionLink(“”Link Text””, “”About””, “”Home””)

• RouteLink will generate a URL to a specific route determined either by name or route values.

@Html.RouteLink(“”Link Text””, new {action=””GoToAbout””})

• The RouteLink method renders an element that links to a URL, which can resolve to an action method, a file, a folder, or some other resource.

What is the difference between HTML.TextBox vs HTML.TextBoxFor ?
Essentially the difference between the html helpers @Html.TextBox() and @html.TextBoxFor() is that the.TextBox is weakly typed and is independent of model and the.TextBoxFor is strongly typed and it should be bound to one of the model properties in strongly typed view. In other words,

• Html.TextBox is a plain text box that isn’t associated with a model’s property. Example:

@Html.TextBox(“”FirstName””)

When this gets passed to your post-action (action on the controller after postback), you’d collect the value by FormsCollection using the string “”FirstName”” as a key.

• When you use, TextBoxFor, while the HTML is generated, it will automatically map the value from the model property to it, in this case, “FirstName”. This will actually generate a textbox that matches your property name and will also populate the textbox with any values that are contained within the Model that was passed in.

@Html.TextBoxFor(model => model.FirstName)

When you post the values of the current page, if your controller is having your model as the parameter, the value can be retrieved directly by accessing the property of the associated model.

• Html.TextBox is used to generate a plain text box that isn’t associated with a model’s property. Html.TextBoxFor is used when you want to associate the property of a model to the textbox. The text box then takes on the name of the property, which makes it convenient to gather all form elements as properties of a model in your post-action.

• The typed TextBoxFor will generate your input names for you. This is usually just the property name but properties of complex types can include an ‘_’ such as ‘customer_name’.

• Using the typed TextBoxFor version will allow you to use compile-time checking. So if you change your model then you can check whether there are any errors in your views.

What is the difference between Html.EditorFor and Html.TextboxFor?
• The Html.TextboxFor creates a textbox with the input type of text. It will always render the input textbox.

• Html.EditorFor is similar to TextBoxFor, however, EditorFor takes on HTML attribute properties based on a model’s data annotations. If you address properties of a model with annotation attributes, the EditorFor helper will try to accommodate a suitable form element for the property. if a property is of type List/Collection/IEnumerable, the EditorFor may render a dropdown list. If the property is of DateTime, the EditorFor may render a date picker (using jquery).

• In most cases, if you use default MVC scaffolding (fancy word for ‘template’), you’ll get EditorFor helpers because MVC assumes the models you’ve created have been properly decorated with annotations.
AJAX HELPER

AJAX Helpers Interview Questions on MVC

What are AJAX Helpers in MVC?
• AJAX Helpers are used to create AJAX-enabled elements like as Ajax enabled forms and links which performs request asynchronously.

• AJAX Helpers are extension methods of AJAXHelper class that exist in the System.Web.Mvc namespace.

• Code for AJAX-enabled link based on action/controller

@Ajax.ActionLink(“Load Products”, “GetProducts”, new AjaxOptions {UpdateTargetId = “Products-container”, HttpMethod = “GET” })

Output: data-ajax-method=”GET”
data-ajax-mode=”replace”
data-ajax-update=”#Products-container”
href=”/Home/GetProducts”>Load Products

Two core features of Ajax helper are as follows:

• You can submit an entire form using Ajax: allows you to submit an entire to an action method. To submit a form using Ajax helper you use BeginForm() helper method…

How can we determine action invoked from HTTP GET or HTTP POST ?
This can be done in the following way –

Use class – HttpRequestBase and use the method – HttpMethod to determine the action request type.

To detect if the call on the controller is a POST action or a GET action we can use the Request.HttpMethod property is shown in the below code snippet.

public ActionResult SomeAction()
{
if (Request.HttpMethod == “POST”)
{
return View(“”SomePage””);
}
else
{
return View(“”SomeOtherPage””);
}
}

How can we restrict MVC actions to be invoked only by GET or POST?
We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls.

For instance, you can see in the below code snippet the DisplayCustomer action can only be invoked by HttpGet. If we try to make an HTTP POST call on DisplayCustomer, it will throw an error.

[HttpGet] public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View(“DisplayCustomer”,objCustomer);
}

[HttpPost] public ViewResult DisplayCustomer(int id)
{
Customer objCustomer =Customers[id];
return View(“DisplayCustomer”,objCustomer);
}

Action Filter Interview Questions on MVC

What are Action Filters in ASP.NET MVC?
• If we need to apply some specific logic before or after action methods, we use action filters.

• We can apply these action filters to a controller or a specific controller action.

• Action filters are basically custom classes that provide a means for adding pre-action or post-action behavior to controller actions.Action Filters in ASP.NET MVCFor example,
• Authorize filter can be used to restrict access to a specific user or a role.
• OutputCache filter can cache the output of a controller action for a specific duration.and more.

Mention some action filters which are used regularly in MVC?
Below are some action filters used –

• Authentication

• Authorization

• HandleError

• OutputCache

How can we restrict MVC actions to be invoked only by GET or POST?

Inline action filter
To create an inline action attribute we need to implement the IActionFilter interface. The IActionFilter interface has two methods: OnActionExecuted and OnActionExecuting. We can implement pre-processing logic or cancellation logic in these methods.

public class Default1Controller : Controller , IActionFilter
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Trace.WriteLine(“”Action Executed””);
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Trace.WriteLine(“”Action is executing””);
}
}

The problem with the inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute.

Creating an ActionFilter attribute
To create an action filter attribute we need to inherit from ActionFilterAttribute and implement the IActionFilter interface as shown in the below code.

public class MyActionAttribute : ActionFilterAttribute , IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Trace.WriteLine(“”Action Executed””);
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Trace.WriteLine(“”Action executing””);
}
}

Later we can decorate the controllers on which we want the action attribute to execute. You can see in the below code, Default1Controller is decorated with the MyActionAttribute class which was created in the previous code.

[MyActionAttribute]

public class Default1Controller : Controller
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
}

Provide some scenarios where ActionFilters can be used?
Action filters are useful in the following scenarios:

• Implement post-processing logic before the action happens.

• Cancel a current execution.

• Inspect the returned value.

• Provide extra data to the action.

• Logging of execution.

If you have any doubt related to these interview questions on MVC ask me in the comment section…

Also-Read: 20+ Basic Interview Questions on Manual Testing

Source: AppShells

Leave a Reply

Your email address will not be published.

%d bloggers like this: