Skip to main content

How to get all model validation errors in ASP.NET MVC?

In ASP.NET MVC you can get a list of all validation errors for your model from the ModelState

if (!ModelState.IsValid)
var modelErrors = new List<string>();
foreach (var modelState in ModelState.Values)
foreach (var modelError in modelState.Errors)
// Here you have the list of error, you can show them on the view or generate a erro string and display it using javascript.

If you want to display it in razor then you can use @Html.ValidationSummary().

Hope it will help to find the actual error from the modal state.

Explore Action Filters in Asp.Net MVC Applications

What is Action Filters

In the Asp.Net MVC application there are controllers, each controller defines action methods that generally have one to one relation ship with views or each actions use performs on the page.
User actions means we can say like clicking on buttons, links or submitting a form. When this kind of action performs request is routed to controller and finds the action method.
Now if we want to perform some action, calculate login or check some values either before calling an action method or after action method completes Action Filters are used.

Asp.Net MVC provides actions filters which we can say custom attributes which provides facility to perform some behavior at pre-action or post-action time of controller action method.

Now lets see the available types of the Action filter in Asp.Net MVC

Action Filter Types

Asp.Net MVC provides 4 types of action filters like Authorization filter, Action filter, Result filter and Exception filter. Please find the below description for each type of action filter.

Authorization filter

Generally it is used to implement authorization and authentication for action method, It is related to security of the application whether to execute action method or not, it also check for the authentication and request property.
As an example you can see AuthorizeAttribute class for Authorization action filter.

Action filter

Generally it is used to perform some extra processing, like before executing any action method we want to check like user is logged in or not, or user has enough permission to execute this action method or not.
If session expired and we want to transfer request to login page etc.

Result filter

Generally it is used to perform extra processing of the result like modifying the response that means if we want to execute a login before or after the view result get executes we can use this filters.
As an example you can see OutputCacheAttribute class for result filter.

Exception filter

It executes when ever there is an unhanded exception thrown by anywhere in the action method. Exception filters can be used for the tasks like logging an error or displaying an error page 404
As an example you can see HandleErrorAttribute class for exception filter.

Interview Questions and Answers for ASP.NET MVC

Nova days ASP.NET MVC is getting more and more popular. ASP.NET MVC has a very good feature called Modal-View-Controller architecture so it is more popular.
In this article we will see the some Question and Answer for ASP.NET MVC which will help you to make your mvc concept clear in short time.
We will keep posting more and more article in this interview series so this will be your unique place to find interview related questions answer.
Now let’s start some important interview question answer related to ASP.NET MVC.

1. What is ASP.NET MVC ?
Most commonly asked question in the interview, ASP.NET MVC is an architectural pattern which separates the UI and code. Mainly it’s divided into 3 Parts Model, View and Controller.
-Model : Model is a real word object, (Database table) and it’s provides data to the View.
-View : View is presentation layer, means it is responsible for the look and feel, We can write html here.
-Controller : Controller is the key part of the architecture, it is mainly responsible for handling request and load the data into model and call the view by passing Model.

2. What is Routing in ASP.NET MVC?
In Classic WebForm development we were doing URL rewriting using web.config file or using third party library. But in ASP.NET MVC it is very easy. Using routing we can display user friendly URL in the browser.
ASP.NET MVC framework using routing engine, which maps URL to Controller/Action. We can define routing rules for URL, so using incoming URL routing engine can send request to proper controller and action method.
When first request come to the routing engine it will collect the URL and check for the routing table, if any proper route found for incoming URL it will redirect request to that route else it will redirect to default route.

3. What are the different ActionResult available in ASP.NET MVC?

There is a main 1 Class call ActionResult but it has many sub classed as below

1. ViewResult – Get the response and render specific view.
2. EmptyResult – Return an empty result
3. ContentResult – Return content(plain text) to the response
4. JsonResult – Return given ViewData object to JSON format
5. PartialViewResult – Renders a specific but partial view to the response
6. RedirectResult – Returns an HTTP redirection to a given URL
7. RedirectToRouteResult – Depending on the routing engine get the URL and redirect the result
8. JavaScriptResult – Return code piece of JavaScript that can later execute on client machine
9. FileContentResult – Returns a file with content to the client
10.FileStreamResult – Returns a file to the client but in the form of a Stream
11.FilePathResult – Returns a file with path to the client

4.What is Web API ‘s in ASP.NET MVC ?
– Web API is a new framework developed by Microsoft to build RESTFul services on HTTP, It is very compatible to call from multiple browsers like web browsers,desktop,mobile, smart phones, tablets etc.

5. What are the display Modes in Asp.Net MVC?
I am never used it till now but what I know about this is Modes are automatically selected, If we are viewing from desktop browser then application return URL
as ‘Views/Authentication/Register.cshtml‘ and for the same request in the mobile browser it will redirect to ‘Views/Authentication/

6. What is Razor in ASP.NET MVC?
The word Razor is used to as a cleaner, so it is just a new style of coding to make it faster. In simple word Razor is a View Engine. In Asp.Net MVC there are major 2 view engine Razor and Asp.Net view.
It is recommended we use Razor view.
See the syntax for both view engine as below

// In Asp.Net View Engine if we want to display a variable
<% foreach (var item in Model)
{ %>
<span> <% item.Name %> </span>
<% }%>

//in ASP.MVC, Razor View if we want to display a variable
@foreach (var item in Model)
<span> @item.Name </span>

7. Is TempData can preserve values between multiple request?

This is very tough question to answer because the answer of this question is YES and NO as well,
Now let me explain how is that
Answer is Yes if TempData variable value is not accessed and you are on multiple request.
Answer is No if TempData variable value is accessed once then it will be null

8. What is TempData in ASP.NET MVC?
TempData is a dictionary type object but it used to access data between multiple redirect, from one controller to another controller or from 1 action to another action.

For example see the below code blog.

//Set TempData in first controller "Category"

public ActionResult Index()
var CategoryModel = new Category()
Name = "Electronics",
TempData["Cat"] = CategoryModel;
return RedirectToAction("Index","Product");

//Access TempData in second controller "Product"
public ActionResult Index()
var CategoryModel= TempData["Cat"];
return View(CategoryModel);

9. What is ViewBag in ASP.NET MVC?
ViewBag is very similar to ViewData and used to maintain state and transfer values between controller to view and next subsequent request, the main difference is
ViewBag doesn’t require a type casting for complex data type because it is dynamic type object so we can use it without type casting. ViewBag and ViewData has a very short life, so it will be null if we redirect to another view or page.
For example see the below code blog.

// Set ViewBag in Controller
Public ActionResult Index()
ViewBag._VarName = "This string is set from Controller";
Return View();

//Use ViewBag in View

10. What is ViewData in ASP.NET MVC?

It is passed to data from controller to view and also in the next subsequent request. It is type of Dictionaty object, so it can save any kind of data with a key value pair including user defined data type. We can set the data in controller and use it in the view.
If it is other then string datatype we need to type case it before we use it to avoid error.
For example see the below code blog.

// Set ViewData in Controller
Public ActionResult Index()
ViewData["VarName"] = "This string is set from Controller";
Return View();

//Use ViewData in View

11. How to transfer values between View and Controller in ASP.NET MVC?
There are multiple ways using that we can transfer values between View and Controller in ASP.NET MVC as below.
1. TempData : Long term data storage as compare to ViewBag and ViewData and is of dictionary type.
2. ViewBag : Short term data storage as compare to TempData and is of dynamic types.
3. ViewData : Short term data storage as compare to TempData and is of Dictionary type.
4. Hidden Fields : It is used to transfer value from View to Controller.
5. Session : It is very power full and dynamic ways to transfer values in Asp.Net MVC, it supports value transfer between Controller to View, View to Controller and Controller to Controller

12. How to navigate request from One view to another ?
It’s very simple you can place a Hyperlink using ‘ActionLink’ Method of Html helper to navigate to destination action.
For example see the below code blog.

<%= Html.ActionLink("ActionName","ControllerName") %>

13. What is Model in Asp.Net MVC?
Model is the main object which retrieves the data into it from database and saved back to the database after setting value to it. In addition to that, if we are not using ViewModel then
it will be useful to validation part and also used to handle business logic if we are not using any business layer. But it is recommended to use separate business logic layer for that and use a ViewModel to handle validation part.

14. Can We use ASP.NET MVC in Windows application?
No. Model, View, controller framework is used to create web applications only.

15. What are the important features of ASP.NET MVC?

– ASP.NET MVC supports Caching, authentication and authorization, Membership and Roles.
– It supports Test driven development using test project.
– It clears the concept of separation of application concerns.

16. What is minification and how it is helpful?
Minification is the process of reducing the file size for CSS and JavaScript, It is removing blank space, comments etc. It also remove white space from CSS and JS
file. Nova days we are using lots of CSS and JS files into our project which increase the page-size thus it’s take time to load on the browser and reduce the performance, but using minification we can reduce the overall size of CSS and JS code so site will load faster.

See below code example how minification reduce the file size.

// Below is the code for what we are writing JavaScript
var firstName = "Tarun";
var lastName = "Dudhatra";
var fullName = firstName + " " + lastName;

//Once we minified above code it will looks like below code snippet

var firstName="Tarun";var lastName="Dudhatra";var fullName=firstName+" "+lastName;

Now with above code you can see that how our JS code reduced.
17. What is Partial View and how it will helpful?
In Asp.Net WebForms we were using User Control for common view or look and feel, in Asp.Net MVC it is replaced with a Partial View. We can call it multiple times or we can use same view for different different page.
There are some method using which we can render our partial view on the page like View.Partial and RenderPartial method.

For example see the below code block


In the above article we have seen very basic and frequently asked Question & Answer, In the upcoming article we will see some more questions.

If you have any comments, suggestions or doubts, please feel free to leave as a comment

Best of Luck