Wednesday, June 10, 2015

ASP.Net MVC Interview Questions and Answers

This is the series of Questions pertinent to MVC and related technology.

Initially will focus on Asp.Net  MVC and here are the few of them started from today,In upcoming days I will keep on adding fresh questions and intent will be to cover up all those scenario which you may encounter in an interview.Here We Go … 




Scenario: Suppose you want to use a partial view but also pass the same model object from the parent view, what HTML Helper would you use?
Answer : Html.Partial() method provide by MVC.
Scenario: How can we create a dynamically generated  form for an entire object based upon the metadata of the object's type using  MVC engine .

Answer : We can use Html.EditorForModel() for this purpose .Than we do not need to pass the model to the helper as a parameter  because it reads directly from the view.For more deep understanding you can go through images shown below:


Output after rendering.


Scenario: What is the use of OutputCacheAttribute in MVC?
Answer : The best use of this attribute is to mark an action method whose output will be cached.
Scenario: You have restricted a Controller so that all actions require the user to be authorized, Now a unauthorized user wants to access a specific action so what will be your approach in order to use  without authorization?
Answer : You should decorate that particular action with AllowAnonymous attribute.

   1:  [AllowAnonymous] 
   2:  public ActionResult WelCome(string DotnetPiper) 
   3:  { 
   4:       return View(); 
   5:  } 

Advantages of MVC Model and ASP.Net Web Forms model.Difference between MVC and Web Forms !!

Answer : Here are some main advantages which may help you to understand which model may be best for for your requirement.

  1. MVC provides clean separation of concerns (SoC) .
  2. MVC allows full control over the rendered HTML you can do amendments as your need.
  3. Enable Test Driven Development (TDD) and easy to test.
  4. Easy integration with JavaScript frameworks which enables rich features.
  5. Support third-party view engines.No ViewState and PostBack events so it is  stateless nature of web.
  6. URL based approach which is famous as Routing.

Advantages of Web Form Model->

  1. Provides Rapid action development.
  2. Provides rich controls.Easy development model and event driven.
  3. Familiar model for windows form developers

To explore MVC further,  I am sharing some interesting facts about the similarities and dissimilarities of MVC and Web Forms.
I have seen many articles that state dissimilarities between both, however there are also few similarities also that I’ll list.
ASP.Net MVC / Web Forms Similarities

The following are some similarities; they both:

  1. Are built on the ASP.Net Framework
  2. Are in the System.Web namespace.
  3. Use .Net Framework supported languages.
  4. Use an IIS and ASP.Net request Pipeline, for example HTTP Handler and HTTP Module.
  5. Send the response back to the client in the form of HTML.
  6. Also support third-party controls.

ASP.Net MVC / Web Forms dissimilarities

The following are some dissimilarities.


ASP.Net Web Forms

View and logic are separate, it has separation of concerns theory. MVC 3 onwards has .aspx page as .cshtml.No separation of concerns; Views are tightly coupled with logic (.aspx.cs /.vb file).
Introduced concept of routing for route based URL. Routing is declared in Global.asax for example.File-based routing .Redirection is based on pages
Support Razor syntax as well as .aspxSupport web forms syntax only.
State management handled via Tempdata, ViewBag, and View Data. Since the controller and view are not dependent and also since there is no view state concept in ASP.NET, MVC keeps the pages lightweight.State management handled via View State. Large viewstate, in other words increase in page size
Partial ViewsUser Controls
HTML HelpersServer Controls
Multiple pages can have the same controller to satisfy their requirements. A controller may have multiple Actions (method name inside the controller class).Each page has its own code, in other words direct dependency on code. For example DotnetPiper.aspx is dependent on Dotnetpiper.aspx.cs (code behind) file
Unit Testing is quite easier than ASP.Net Web forms Since a web form and code are separate files.Direct dependency, tight coupling raises issues in testing.
URL basedEvent Driven
layoutsMaster Pages

I hope these facts may help you to understand the similarities and dissimilarities between MVC and Web Forms .I tried to keep it simple to understand the fact in an easier manner.

TempData, Keep and Peek methods in MVC4 and its uses.

Answer : An Intension to write something on these keywords Keep and Peek to abolish confusion.Actually if we look at the definition of Keep and Peek method shown below:

Keep-> It marks the specified keys to keep in dictionary memory.

Peek-> it returns an object contains an element without marking object for deletion in Dictionary.

Let’s look in practical approach and abolish confusion if someone has Smile . TempData value persist at successive request and can transmit from Controller to View. After transferring TempData value from controller to View ,if you again try to use it at other level than it will lost its value and become null. TempData is used to pass data from current request to subsequent request from one level to another level e.g. controller to view, controller to action to another action.I’ve two action methods of a same controller and performed some steps in order to verify the authenticity of methods.

  1:  public ActionResult Verify()
  2:         {
  3:             ICollection<ModelState> collection = ModelState.Values;
  4:             //return View("Verify", dbContext.EmpRegistrations.Single(x => x.Id == 111111));
  5:             if (TempData["EmployeeRegistration"] != null)
  6:             {
  7:                 TempData["EmployeeRegistration"] = ObjEmp.GetEmpRegistrationsDetails();
  8:                 TempData.Keep("EmployeeRegistration");
  9:             }
 10:             else
 11:             {
 12:                 TempData["EmployeeRegistration"] = ObjEmp.GetEmpRegistrationsDetails();
 13:                 TempData.Keep("EmployeeRegistration");
 14:             }
 15:           return View("Verify", TempData["EmployeeRegistration"]);
 16:         }


  1:  public ActionResult Details(int id)
  2:         {
  4:             var checkViewDataValue = TempData.Peek("EmployeeRegistration");
  5:             return View();
  6:         }

When I start execution with Verify action it sets its value in TempData and used Keep method to retain its value for further cycle as you can see in Verify action.

Now in the Details action I have brought in the value in variable from TempData using Keep method.However if I hit the same URL (http://localhost:60346/Register/Details/1) again to verify its value existence than it doesn’t retain as shown below in image:


To retain its value again you have to use Keep method again. Because the key in TempData dictionary is marked for deletion when it is read and is deleted at the end of HTTP Request.On the other hand Peek method is used to read data from TempData without marking the key in the dictionary for deletion.

  1:  public ActionResult Details(int id)
  2:         {
  3:            var checkViewDataValue = TempData.Peek("EmployeeRegistration");
  4:             return View();            
  5:         }

If you are reterving the data using Peek method than there is no need to retain data using Keep method again and again.Peek is best in use to retrieve data from TempData.This is most FAQ in an Interview.

Stay Tuned for more questions ….

How can we handle exception in MVC4 and at how many level?

Answer : We have a HandleError Attribute to handle the errors.You can handle an error at different level

1.Global Level

2.Controller level

3. Action Level

In below code snippet states you various ways to define and handle an error.

The HandleError Attribute filter works only when custom errors are enabled in the Web.config file of your application. You can enable custom errors by adding a customErrors attribute inside the <system.web> node, as depicted below:

  1:  <customErrors mode="On" defaultRedirect="Error" />

This is the way to handle an error at Global Level.

  1:  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  2:         {
  3:             //Register multiple filters are applied with ascending Order (default = -1)
  5:             //database errors
  6:             filters.Add(new HandleErrorAttribute
  7:             {
  8:                 ExceptionType = typeof(System.Exception),
  9:                 View = "Error", // Shared folder error page //Error.cshtml
 10:                 Order = 1
 11:             });
 12:             filters.Add(new HandleErrorAttribute() { Order = 1 });
 13:         }

HandleError attribute @ Action level:

  2:         [HandleError(ExceptionType = typeof(System.InvalidOperationException), View = "Error")]
  3:         public ActionResult Verify()
  4:         {
  5:             ICollection<ModelState> collection = ModelState.Values;
  6:             return View("Verify", dbContext.EmpRegistrations.Single(x => x.Id == 111111));
  7:         }

And this is same way to defined attribute at Controller level.

So whenever you execute you Controller/action or it generates an error than it redirects to Error.cshtml page and shows you a custom error as shown below:


How can we override the action names in MVC?

Answer : If we want to override the action names we can do like this –

  1: [ActionName("DotnetPiper")]
  2: public ActionResult VerifyAction() {
  3: return View();
  4: }
How to restrict the users to request the method/Action directly in the browser's URL ?
Answer- There are probably certain ways to achieve the result .Two of them are shown below :
Using ChildActionMethod allows you to restrict access to action methods that you would not want users to directly request in the browser's URL.
  1: [ChildActionOnly]
  2: public ActionResult DotnetPiper()
  3: {  
  4:   return View();
  5: }
To know more in depth please visit this link : CHILD ACTION METHODS IN ASP.NET MVC4
Option 2.
In Asp.Net MVC each method of controller is access by URL and in case we have created an action which should not be accessible via URL than 
MVC provides you way to protect your action method via NonAction attribute.
After declaring method as NonAction if you want to access method/action via url. It will return HTTP 404 not found error.
  1: [NonAction]
  2: public ActionResult DotnetPiper()
  3: {    
  4:     return "";\
  5: }

What is the difference between ActionResult and ViewResult()?

Answer :

ActionResult is an abstract class and it is base class for ViewResult class.ActionResult is a general result type that can have several subtypes like ViewResult,PartialViewResult,JsonResult,ContentResult etc.

ViewResult is an implementation for this abstract class. It finds a view page .cshtml or .aspx in some predefined paths in view folder like (/views/controllername/, /views/shared/, etc) by the given view name.

If you are sure that your action method will return some view page, you can use ViewResult. and definitely it may possible that if action method may have different behavior other than view like Redirect to Action,Content Result . You should use the base class ActionResult as the return type

How we can overload the action in MVC?

Answer- If we want to overload the action names we can do like this –

  1: public ActionResult VerifyAction() 
  2: {
  3:   return Content("Welcome to DotnetPiper");
  4: }
  6: [ActionName("DotnetPiper")]
  7: public ActionResult VerifyAction()
  8: {
  9:   return Content("Welcome to DotnetPiper"); 
 10: }
To access above overload method please type given below URL in browser:
 If there are two controllers exists with the same name in a solution than how ASP.Net MVC handles such scenario.

Answer: Asp.Net provides you way to resolve such issue after putting Namespace as parameter at time of defining Route. Kindly refer an image below to understand how it actually works:


  1:  routes.MapRoute(
  2:                "DefaultRegister", // Route name
  3:                "{controller}/{action}/{id}", // URL with parameters
  4:                new { controller = "Register", action = "Verify", id = UrlParameter.Optional },// Parameter defaults
  5:                new[] { "MVCSample.Controllers" }   // Namespaces
  6:            );
Kindly add your valuable thoughts if you feel that it could happen in some better way.

To know more MVC and WebApi Kindly go through with these links

MVC Articles & WCF and WebAPI



  1. Excellent post!!! The future of .net application development is on positive note. It offers huge career prospects for talented professionals all over the world. Training on .net technology will ensure good salary package. Best DOT NET Training institute in Chennai | DOT NET Training Institutes in Chennai

  2. Hello , I have been training students on AngularJS for past 6 months, and at times, I have used your blog as reference for the class training and also for my personal project development. It has been so much useful. Thank you, keep writing more:)
    AngularJS training Chennai

  3. Oracle DBA Training in Chennai
    Thanks for sharing this informative blog. I did Oracle DBA Certification in Greens Technology at Adyar. This is really useful for me to make a bright career..

  4. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
    Websphere Training in Chennai

  5. Data warehousing Training in Chennai
    I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..

  6. Selenium Training in Chennai
    Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

  7. Oracle Training in chennai
    Thanks for sharing such a great information..Its really nice and informative..

  8. SAP Training in Chennai
    This post is really nice and informative. The explanation given is really comprehensive and informative..

  9. This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post,thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic
    Android Training In Chennai In Chennai

  10. Pretty article! I found some useful information in your blog, it was awesome to read,thanks for sharing this great content to my vision, keep sharing..
    Unix Training In Chennai

  11. I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    SalesForce Training in Chennai

  12. There are lots of information about latest technology and how to get trained in them, like Best Hadoop Training In Chennai in Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies Hadoop Training in Chennai By the way you are running a great blog. Thanks for sharing this blogs..

  13. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..
    Informatica Training in chennai | QTP Training in Chennai

  14. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    Oracle Training In Chennai | Hadoop Training In Chennai

  15. Best Java Training Institute In ChennaiThis information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..

  16. This is very helpful post with nice content thanks for sharing keep sharing Company About Us

  17. You shared useful post. I like your post. Thanks !

    Magento Development in Chennai

  18. Thanks for your post. Very interesting also good information.