Initially I will focus on ASP.NET MVC interview questions and here are few of them starting from today. In upcoming articles, I will keep on adding fresh questions and intent will be to cover up all those scenarios which you may encounter in an interview. Here we go,
Question: 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.
Question: 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, then 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 the following images:
Output after rendering.
Question: 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.
Question: You have restricted a Controller so that all actions require the user to be authorized. Now an unauthorized user want 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.
- [AllowAnonymous]
- public ActionResult WelCome(string DotnetPiper)
- {
- return View();
- }
Question: 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 the best for your requirement.
- MVC provides clean separation of concerns (SoC).
- MVC allows full control over the rendered HTML you can do amendments as your need.
- Enable Test Driven Development (TDD) and easy to test.
- Easy integration with JavaScript frameworks which enables rich features.
- Support third-party view engines.No ViewState and PostBack events so it is stateless nature of web.
- URL based approach which is famous as Routing.
Advantages of Web Form Model
- Provides Rapid action development.
- Provides rich controls.Easy development model and event driven.
- 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 stating dissimilarities between both, however I will also list some similarities.
ASP.NET MVC / Web Forms Similarities
The following are some similarities; they both:
- Are built on the ASP.Net Framework.
- Are in the System.Web namespace.
- Use .Net Framework supported languages.
- Use an IIS and ASP.Net request Pipeline, for example HTTP Handler and HTTP Module.
- Send the response back to the client in the form of HTML.
- Also support third-party controls.
ASP.NET MVC / Web Forms dissimilarities
The following are some dissimilarities.
ASP.NET MVC | 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 .aspx | Support 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 Views | User Controls |
HTML Helpers | Server Controls |
Multiple pages can have the same controller to satisfy their requirements. A controller may have multiple Actions (method name inside the controllerclass). | 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 based | Event Driven |
layouts | Master 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.
Question: TempData, Keep and Peek methods in MVC4 and its uses practically.
Answer: An intention to write something on these keywords Keep and Peek to abolish confusion. Here are the definition of Keep and Peek method:
- 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 at a practical approach and abolish confusion if someone has. 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 controller. One 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.
- public ActionResult Verify()
- {
- ICollection<ModelState> collection = ModelState.Values;
-
- if (TempData["EmployeeRegistration"] != null)
- {
- TempData["EmployeeRegistration"] = ObjEmp.GetEmpRegistrationsDetails();
- TempData.Keep("EmployeeRegistration");
- }
- else
- {
- TempData["EmployeeRegistration"] = ObjEmp.GetEmpRegistrationsDetails();
- TempData.Keep("EmployeeRegistration");
- }
- return View("Verify", TempData["EmployeeRegistration"]);
- }
- public ActionResult Details(int id)
- {
- var checkViewDataValue = TempData.Peek("EmployeeRegistration");
- return View();
- }
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.
- public ActionResult Details(int id)
- {
- var checkViewDataValue = TempData.Peek("EmployeeRegistration");
- return View();
- }
If you are retrieving the data using Peek method, then their is no need to retain data using Keep method again and again. Peek is best in use to retrieve data from TempData. This was the question that is generally asked in an Interview.
Stay Tuned for more questionsQuestion: 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 the following different levels:
- Global Level
- Controller level
- Action Level
In the following code snippet, various ways to define and handle an error is provided.
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:
- <customErrors mode="On" defaultRedirect="Error" />
This is the way to handle an error at Global Level.
- public static void RegisterGlobalFilters(GlobalFilterCollection filters)
- {
-
-
-
- filters.Add(new HandleErrorAttribute
- {
- ExceptionType = typeof(System.Exception),
- View = "Error",
- Order = 1
- });
- filters.Add(new HandleErrorAttribute() { Order = 1 });
- }
HandleError attribute @ Action level:
- [HandleError(ExceptionType = typeof(System.InvalidOperationException), View = "Error")]
- public ActionResult Verify()
- {
- ICollection<ModelState> collection = ModelState.Values;
- return View("Verify", dbContext.EmpRegistrations.Single(x => x.Id == 111111));
- }
And this is same way to defined attribute at Controller level.
So whenever you execute your Controller/action or it generates an error, then it redirects to Error.cshtml page and shows you a custom error as in the following screenshot:
Question: How can we override the action names in MVC?
Answer: If we want to override the action names we can do like this –
- [ActionName("DotnetPiper")]
- public ActionResult VerifyAction() {
- return View();
- }
Question: 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:
Option 1
Using ChildActionMethod allows you to restrict access to action methods that you would not want users to directly request in the browser's URL.
- [ChildActionOnly]
- public ActionResult DotnetPiper()
- {
- return View();
- }
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, then 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.
- [NonAction]
- public ActionResult DotnetPiper()
- {
- return "DotnetPiper.com";\
- }
Question: 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 such as 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 maybe it is 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.
Question: How we can overload the action in MVC?
Answer: If we want to overload the action names we can do like the following code snippet:
- public ActionResult VerifyAction() {
- return Content("Welcome to DotnetPiper");
- }
- [ActionName("DotnetPiper")]
- public ActionResult VerifyAction() {
- return Content("Welcome to DotnetPiper");
- }
To access above overload method please type the following URL in the web browser:
http://localhost:57964/Home/DotnetPiper Question: 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 a parameter at the time of defining Route. Kindly refer the following image to understand how it actually works:
- routes.MapRoute(
- "DefaultRegister",
- "{controller}/{action}/{id}",
- new {
- controller = "Register", action = "Verify", id = UrlParameter.Optional
- },
- new [] {
- "MVCSample.Controllers"
- }
- );
Question: Which base class can be used for the return value of an MVC action method?
Answer: ActionResultQuestion: Which of these formats is not supported out of the box by Web API?
Answer: Form URL-encoded, JSON and XML.
Execution order of filters in MVC 4 with practices: important faq.
There are the following types of filters that can be implemented to inject custom processing logic.
- Authorization filter
- Action filter
- Result filter
- Exception filter
In MVC 5 a new filter has been added Authentication. The order of execution will be the following if we add that also:
- Authentication Filter
- Authorization filter
- Action filter
- Result filter
- Exception filter
For more detail, here's the link:
How can you restrict access to a Controller, action?
Answer: You can restrict access to a Controller, action using Authorize attribute so that only authorized users can made an attempt to it.
Question: What is the type of the ViewBag property?
Answer: Dynamic
Question: If you have a _Layout.cshtml file in your shared views, which file can you create to have custom layout for mobile platforms?
Answer: _Layout.mobile.cshtml
Question: What is ChildActionOnlyAttribute?
Answer: A Method that is decorated with ChildActionOnlyAttribute can be called only with the Action or RenderAction HTML extension methods.
Kindly add your valuable thoughts if you feel that it could be done in a better way.