Below is video covering 25 most important ASP.NET MVC Interview Questions and Answers do refer the same: -
C# and .NET step by step with interview questions
Wednesday, March 17, 2021
Saturday, February 27, 2016
Learn ASP.NET MVC step by step: - Part 1
Contents
Learn ASP.NET MVC step by step: - Part 1 Step 1: Download & Install Microsoft Visual Studio 2013 Ultimate Step 5: Putting code in the controller and view Step 7: Creating the student model Step 8: Adding the students controller Step 9: Creating the students screen Step 10: Writing logic for Submit click This article series is targeted for freshers who want to learn ASP.NET MVC. So if you are senior then I would suggest to start from this MVC article. So in this two partarticle I will be creating a simple student data entry screen using ASP.NET MVC , ADO.NET and Jquery. I have used the below youtube video for reference purpose. And would encourage any new ASP.NET MVC learner to first see this videoto get a good kick start. I have broken this tutorial in to two parts. In part 1 we will see what we need to start MVC , we will learn the basics of creating controller , models and view and then we would create a simple student data entry screen and see how it works with the HTTP Post and submit. In the next article we will learn validations both client side and server side and also we will looking to how to interact with SQL Server using ADO.NET. For doing ASP.NET MVC the first thing we need is visual studio. So go ahead and install visual studio from the below link. http://www.microsoft.com/en-US/download/details.aspx?id=44915Introduction
Step 1: Download & Install Microsoft Visual Studio 2013 Ultimate
Step 2: Creating project
Visual studio is an official IDE for doing any kind of Microsoft development work. And to do any Microsoft development we need to create a project. So click on file – menu and project as shown in the below figure.
As said previously visual studio is used to do any kind of development like Windows, mobile , web and so on. So when we say ASP.NET MVC it is for web application. So select Visual C# à Web à ASP.Net Web Application àEnter File NameàPress ok as shown in the below figure.
Now remember ASP.NET is the main framework on which MVC, WebAPI , Webforms and other web programming technologies work. So once you create the project you will get lot of options, select MVC from the same as shown below.
Also change Authentication to “No Authentication” for now. We will learn more about authentication and authorization later. Lets first get our simple hello world project running and keep complicated things later.
Once you click ok you should see the MVC project created with all necessary files as shown below. Do not get too much confused about the folder and file structure for now. For now concentrate on only three folders “Controller”, “View” and “Model”.
Step 3: Add a New Controller
In MVC architecture the first hits comes to controller, which in turn loads the model data and this model data is then sent to the view. So the first step is to create the controller. If you see the solution there is a controller folder. So let us add a new controller by click on the Controllers folderà Add àController.
The next thing you will see is lot of readymade controller templates. But because we are learning let’s not use any readymade templates let’s start from scratch and select MVC 5 controller empty.
Now when we add a controller, do not delete the word controller from the file name. For example if you want to create a “Home” controller then the full name of the file is “HomeController”. The word “Controller” should be present.
4.3: Enter the Name Of Controller as Home.
Step 4: Add a view
So now that we have added controller, lets add view. To add view go to views folder and add view as shown below.
Give a proper view name and uncheck the “user layout page” box.
Finally you should see controller and views added in the respective folder as shown below.
Step 5: Putting code in the controller and view
So let’s start putting some code in Hompage.cshtml (HomePage View). In the HomePage.cshtml we have put a simple hello world text.
In the controller let’s add a simple “ActionResult” method called as “GotoHome” and in that we are returning the view.
namespaceHelloWorld.Controllers
{
publicclassHomeController : Controller
{
//
// GET: /Home/
publicActionResult Index()
{
return View();
}
publicActionResultGotoHome()
{
return View("HomePage");
}sp; }
}
}
Step 6: Run the project
So once you are done with the previous steps just press control + f5 and run the project. It’s possible you get a below error as shown below. Do not get discouraged. This error comes because you have not specified the controller and action name.
On the browser URL type your controller name (without the word controller) followed by action name as shown below. In our case we have “Home” controller and action name is “GotoHome” and you should be able to see the output.
Step 7: Creating the student model
Till now we have not added any model. So let us go ahead and create a simple model by the name students. A model is nothing but a class. So right on models folder and add a class as shown in the below figure.
In the model we have created four properties for the class as shown below.
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
namespaceHelloWorld.Models
{
publicclassStudent
{
publicstringStudentRollNo{ get; set; } //Student Roll No.
publicstringStudentName{ get; set; } //Student Name.
publicstringStudentStd{ get; set; } //Student Standard.
publicstringStudentDIV { get; set; }//Student Divsion.
}
}
Once you write the coderebuild the solution. I again repeat do not miss this step REBUILT THE SOLUTION.
Step 8: Adding the students controller
Let’s add a students controller from where we invoke the data entry screen for the students.
In the controller do not forget to import model namespace.
Lets add an action “Enter” which will invoke the data entry screen.
Step 9: Creating the students screen
So we have completed the model and the controller let us add a view for the same. So right click on the “Enter” Action and click add view as shown in the below figure.
Lets give the view name as “EnterStudent” and uncheck the layout page box. Layout pages are like master pages in ASP.NET webforms.
In view let’s put the below code which has four textboxes for the student data and one submit button.
So now the user will enter data and click on Submit button , we need some kind of logic in the controller for handling the submit click.
Step 10: Writing logic for Submit click
To handle the submit click we need to create submit action in the student controller.
When this submit action is called the data sent from the form will be collected and displayed in a view. Let us add a new view with name “Student” to this submit action.
This view we will connect with the model namespace where we have the customer controller.
Below is the view of the student.
When the user click on submit we need to send data to the submit action. So on the form given the action name as “Submit” and method as “Post”. And also ensure that all textboxes are provided with a name as shown in the below code. For now keep name of the textbox and the class property names same.
In the submit action we will use the request object to fetch data and load the student object and this student object is sent to “Student” view which we have created.
publicActionResult Submit()
{
Studentobj = newStudent();
obj.StudentRollNo=Request.Form["StudentRollno"];
obj.StudentName = Request.Form["StudentName"];
obj.StudentStd = Request.Form["StudentStd"];
obj.StudentDIV = Request.Form["StudentDiv"];
return View("Student",obj);
}
In this the student view we are displaying the values by using the “Model” object as shown below.
Step 11: Run the application
So now that all the hard work is done, take a deep breath and press control + f5 and enter the URL in format of controller name/action name :- http://localhost:22144/student/Enter
Enter data in to the text boxes and press submit.
And you should see this screen.
CodeProjectMonday, May 25, 2015
What is CSRF attack and how can we prevent the same in MVC?
CSRF (Cross site request forgery) is a method of attacking a website where the attacker imitates a.k.a forges as a trusted source and sends data to the site. Genuine site processes the information innocently thinking that data is coming from a trusted source.
For example conside the below screen of a online bank. End user’s uses this screen to transfer money.

Below is a forged site created by an attacker which looks a game site from outside, but internally it hits the bank site for money transfer.

The internal HTML of the forged site has those hidden fields which have the account number and amount to do money transfer.

Now let’s say the user has logged in to the genuine bank site and the attacker sent this forged game link to his email. The end user thinking that it’s a game site clicks on the “Play the Ultimate Game” button and internally the malicious code does the money transfer process.

So a proper solution to this issue can be solved by using tokens: -
- End user browses to the screen of the money transfer. Before the screen is served server injects a secret token inside the HTML screen in form a hidden field.
- Now hence forth when the end user sends request back he has to always send the secret token. This token is validated on the server.

Implementing token is a two-step process in MVC: -
First apply “ValidateAntiForgeryToken” attribute on the action.
[ValidateAntiForgeryToken]
public ActionResult Transfer()
{
// password sending logic will be here
return Content(Request.Form["amount"] +
" has been transferred to account "
+ Request.Form["account"]);
}
Second in the HTML UI screen call “@Html.AntiForgeryToken()” to generate the token.

So now henceforth when any untrusted source send a request to the server it would give the below forgery error.

If you do a view source of the HTML you would find the below verification token hidden field with the secret key.
CodeProjectTuesday, May 19, 2015
How to handle multiple Submit button issues in ASP.NET MVC? (MVC Interview Questions)
How to handle multiple Submit button issues in ASP.NET MVC? (MVC Interview Questions)
Let us understand the above problem in more detail.
Take a scenario where you have a view with two submit buttons as shown in the below code.

In the above code when the end user clicks on any of the submit buttons it will make a HTTP POST to “Action1”.
The question from the interviewer is: -
“What if we have want that on “Submit1” button click it should invoke “Action1” and on the “Submit2” button click it should invoke “Action2”.”
There are three basic approaches to solve the above problem scenario.
HTML way: -
In the HTML way we need to create two forms and place the “Submit” button inside each of the forms. And every form’s action will point to different / respective actions. You can see the below code the first form is posting to “Action1” and the second form will post to “Action2” depending on which “Submit” button is clicked.

AJAX way: -
In case you are an AJAX lover this second option would excite you more. In the Ajax way we can create two different functions “Fun1” and “Fun1”, see the below code. These functions will make Ajax calls by using JQUERY or any other framework. Each of these functions is binded with the “Submit” button’s “OnClick” events. Each of these function make call to respective action names.
Using “ActionNameSelectorAttribute”: -
This is a great and a clean option. The “ActionNameSelectorAttribute” is a simple attribute class where we can write decision making logic which will decide which action can be executed.
So the first thing is in HTML we need to put proper name’s to the submit buttons for identifying them on the server.
You can see we have put “Save” and “Delete” to the button names. Also you can notice in the action we have just put controller name “Customer” and not a particular action name. We expect the action name will be decide by “ActionNameSelectorAttribute”.
So when the submit button is clicked, it first hits the “ActionNameSelector” attribute and then depending on which submit is fired it invokes the appropriate action.

So the first step is to create a class which inherits from “ActionNameSelectorAttribute” class. In this class we have created a simple property “Name”.
We also need to override the “IsValidName” function which returns true or flase. This function is where we write the logic whether an action has to be executed or not. So if this function returns true then the action is executed or else it is not.
public class SubmitButtonSelector : ActionNameSelectorAttribute
{
public string Name { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, System.Reflection.MethodInfo methodInfo)
{
// Try to find out if the name exists in the data sent from form
var value = controllerContext.Controller.ValueProvider.GetValue(Name);
if (value != null)
{
return true;
}
return false;
}
}
The main heart of the above function is in the below code. The “ValueProvider” collection has all the data that has been posted from the form. So it first looks up the “Name” value and if its found in the HTTP request it returns true or else it returns false.
var value = controllerContext.Controller.ValueProvider.GetValue(Name);
if (value != null)
{
return true;
}
return false;
This attribute class can then decorated on the respective action and the respective “Name” value can be provided. So if the submit is hitting this action and if the name matches of the HTML submit button name it then executes the action further or else it does not.
public class CustomerController : Controller
{
[SubmitButtonSelector(Name="Save")]
public ActionResult Save()
{
return Content("Save Called");
}
[SubmitButtonSelector(Name = "Delete")]
public ActionResult Delete()
{
return Content("Delete Called");
}
}
CodeProject
Friday, October 31, 2014
Difference Between ViewResult() and ActionResult() in MVC ?
So without wasting time let’s get the difference in one sentence:-
“ActionResult is an abstract parent class from which ViewResult class has been derived”.
So when you see MVC controller and action codes as shownbelow :-
public ActionResult Index()
{
return View(); // this is a view result class
}
The above code means that you are returning a “ViewResult” object and due to polymorphism this object is automatically type casted to the parent class type i.e “ActionResult”.In case you are newbie to polymorphism , let’s do a quick revision. In polymorphism parent class object can point towards any one of its child class objects on runtime. For example in the below code snippet we have parent “Customer” class which is inherited by “GoldCustomer” and “SilverCustomer” class.
public class Customer
{}
public class GoldCustomer : Customer
{}
public class SilverCustomer : Customer
{}
So down the line later during runtime your parent “Customer” object can point to any one of the child object i.e “GoldCustomer” or “SilverCustomer”.Customer obj = new Customer();
obj = new GoldCustomer();
obj = new SilverCustomer();
How does this polymorphism benefit for MVC results?MVC applications are used to create web sites or web application. Web applications work in a request and response structure because they follow HTTP protocol.
So the end user using theUI sends a HTTP POST or a GET request and the web application depending on scenarios sends a response. Now the request is quiet standard but the response types differ due to different kind of devices.
For example if its a browser you expect HTMLresponse, if its jquery you expect JSON format or for some other client types you just want simple text contents and so on.
So what the MVC team did is they created a base general class called “ActionResult” which was further inherited to create different types of results.
So in the action result code you can pass some parameter from the UI and depending on this parameter you can send different response types. For instance in the below example we are passing a boolean flag whether it’s a HTML view or not and depending on the same we are streaming different views.
public ActionResult DynamicView(bool IsHtmlView)
{
if (IsHtmlView)
return View(); // returns simple ViewResult
else
return Json(); // returns JsonResult view
}
Cool isn’t it rather than writing different methods for each response you just have one method with dynamic polymorphic response.There are 11 different response types which can be sent to the end user :-
- ViewResult - Renders a specified view to the response stream
- PartialViewResult - Renders a specified partial view to the response stream
- EmptyResult - An empty response is returned
- RedirectResult - Performs an HTTP redirection to a specified URL
- RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
- JsonResult - Serializes a given object to JSON format
- JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
- ContentResult - Writes content to the response stream without requiring a view
- FileContentResult - Returns a file to the client
- FileStreamResult - Returns a file to the client, which is provided by a Stream
- FilePathResult - Returns a file to the client








































