ASP.NET MVC Interview Questions and Answers (162) - Page 3

What is significance of 'using' in MVC?

Content Here.....
It ensures that an object is disposed when it goes out of scope.
How to add stylesheet in view in Asp.Net Mvc?

Add stylesheet :

<link rel="StyleSheet" href="@Href(~Content/Site.css")" type="text/css"/>
What is MvcSiteMapProvider ?

It is a tool that provides flexible menus, breadcrumb trails, and SEO features for the .NET MVC framework, similar to the ASP.NET SiteMapProvider model.

You can download it as free through NuGet package for .NET MVC 2.0/3.0/4.0
How to call an action Method on the click of a link?

NOTE: This is objective type question, Please click question title for correct answer.
What is right way to define the routes.MapRoute() method in MVC?

NOTE: This is objective type question, Please click question title for correct answer.
What is cross site request forgery (CSRF) in web application?

Cross Site Request Forgery (CSRF) is a type of attack on the web application or on the website where a malicious user can insert or update data on behalf of the logged in user of the application by giving him a link that is not of the victim website but attackers own website.

In this type of attack the victim website user doesn't know that by clicking on malicious user link he is helping him to update malicious data into his website.

This generally happen by posting data on the victim website by a hidden form and submitting in using JavaScript or jQuery automatically.
How to avoid Cross Site Request Forgery (CSRF) in ASP.NET MVC?

To avoid Cross Site Request Forgery (CSRF) in ASP.NET MVC, you need to do two things.

1. Add [ValidateAntiForgeryTocken] attribute in the Controller Action method which is executing when the form data is being submitted.

2. Add @Html.AntiForgeryTocken() element in the HTML form.
What different types of Scaffold templates are there in ASP.NET MVC?

There are 6 different types of Scaffold templates in ASP.NET MVC that is used to create a view automatically based on the Model selected.

It creates an empty view and only model type is specified in the View page using @model

It creates a view with a form that helps to create a new record for the model. It automatically generates a label and input field for each property in the Model.

Delete :
It creates a view with the list of records from the Model collection along with Delete link to delete records.

It creates a view that displays a lable and the value of each property of the Model.

It creates a view with a form for editing existing model data. It also generates a form with label and field for each property of the Model.

It creates a view with html table that lists the model from the Model collection. It generates html table column for each property of the model. In general, it accepts IEnumerable<ModelType> and iterate through each item of the Enumerable collection. It automatically renders edit, delete links for each record of the Model collection in a column and Create link on the page that target to Create action.
What is the use of ViewStart in ASP.NET MVC?

In the default template of ASP.NET MVC, we get _ViewStart.cshtml page that is used to almost similar to MasterPage in ASP.NET Web Form or like a layout template.

The code of ViewStart executes before the actual view code executes. By default, _ViewStart template is applied to all view files of this or any sub directory under this directory.

The _ViewStart.cshtml file contains following code.


Layout = "~/Views/Shared/_Layout.cshtml";

As this code runs before any view code so we have flexibility to specify a different Layout for a particular view.

Because this code runs before any view, a view can override the Layout property and choose a different
How to write dashed attributes of html (5) element using ASP.NET MVC Helper methods?

To write dashed attribute of HTML element using ASP.NET MVC Helper methods, we replace "-" with "_" in the anonymous type parameter. eg.

@using (Html.BeginForm("Create", "Home", FormMethod.Post,

new { data_validatable=true }))

returns below output

<form action="/Home/Create" method="Post" data-validatable="true" >

Notice, the data-validate attribute of the form element.
What is the use of Html.ValidationSummary helper method in ASP.NET MVC?

The Html.ValidationSummary helper method is used to display all validation errors in the ModelState dictionary, either model property level or errors associated with ModelState.

Model Property level errors are errors that are set as an attributes of the property of the Model. eg


[StringLength(100, ErrorMessage="The Title must not be more than 100 characters long.")]
public string Title { get; set; }

In the above code, the Title field is a mandatory field and can only accept 100 characters.

The ModelState level errors are errors that are set by developer in the Controller by using below code snippet.

ModelState.AddModelError("", "There is an error!");

In this case, the error will be displayed in place of Validation summary like this

<div class="validation-summary-errors">

<li>There is an error!</li>

What should be the attribute for a Model property that corresponds to the Identity column of the database?

The attribute in the Model field for the Identity column of the database should be DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity) like below

public int CategoryId { get; set; }

In case we are returning anonymous type from Controller to the views, what should be the @model in the View?

NOTE: This is objective type question, Please click question title for correct answer.
What is MVC?

MVC is a framework pattern that splits an application logic into three different roles: Model, View and Controller.

Model: Business entity on which overall application operates.MVC does not specifically mention the Data access layer as it is encapsulated by the model.

View: User interface that renders the model into a form of interaction.

Controller: Handles the request from the view and updates the model resulting in a change in model's state.

These are the three important classes(model, view and controller) required for MVC architecture.
What does Separation of concerns means?

The process of breaking a computer program into various features that overlap in functionality implies Separation of concerns.
MVC separates the content from presentation and data-processing from content.
What is ViewStart in MVC?

For group of views that all use the same layout, this can get a bit redundant and harder to maintain.
The _ViewStart.cshtml page can be used to remove this redundancy. The code within this file
is executed before the code in any view placed in the same directory. This fi le is also recursively applied to any view within a subdirectory.
When we create a default ASP.NET MVC project, we find there is already a _ViewStart
.cshtml fi le in the Views directory. It specifi es a default layout:
Layout = "~/Views/Shared/_Layout.cshtml";
Because this code runs before any view, a view can override the Layout property and choose a different one. If a set of views shares common settings, the _ViewStart.cshtml file is a useful place to consolidate these common view settings. If any view needs to override any of the common settings, the view can set those values to another value.
How will the data gets passed between controller and views?

The controller gets the first hit and loads the model. Most of the time we would like to pass the model to the view for displaying data and so we use session variables, viewstate and so on. But the problem with using sessions or view state object is the scope. ASP.NET sessions have session scope and the view state have page scope. In MVC, we would like the data to be maintained when the hit comes to the controller and reaches the view and after that the scope of the data should expire.

That’s where the new session management technique has been introduced in the ASP.NET MVC framework, i.e., ViewData.
How to save data entered from front-end into a pdf file?

public ActionResult SaveResumeAsPdf(FormCollection fc)
if (Session["UserName"] != null)
BaseFont font = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1250, false);
PdfContentByte _pcb;
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/Resumes/" + Session["UserName"] + ".pdf"), FileMode.Create));
_pcb = writer.DirectContent;
_pcb.SetFontAndSize(font, 14);
int count = 30;
foreach (string item in fc.AllKeys)
_pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, item, 50, 780 - count, 0);
_pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, fc[item], 250, 780 - count, 0);
count = count + 30;
How to use two models in a single class?

Whenever you want to use two models in a single view, then add the models to the view in the following way,

@using MvcSampleCFA_02032014.Models;
@model Tuple<PersonCFA, AddressCFA>

Now, you can access all the properties present in the two models.
Why do we use Repositories?

Repositories are minly used in MVC. It does not mean creating the database by itself or storing the data anywhere. It is just an approach in MVC. As we have n-tier architecture in, similarly repositories are a kind of architecture in MVC where we can create a repository class and write all the business logic in this class. We can just call this method from controller and there is no need to write any kind of business logic which makes our controller simple.
Found this useful, bookmark this page to the blog or social networking websites. Page copy protected against web site content infringement by Copyscape

 Interview Questions and Answers Categories