For MVC Interview Questions Part 1 refer below link:
1. What are ViewData, ViewBag and TempData?
MVC provides us ViewData, ViewBag and TempData for passing data from controller, view and in next requests as well. ViewData and ViewBag are similar to some extent but TempData performs additional roles.
2. What are the roles and similarities between ViewData and ViewBag?
Ø Maintains data when moving from controller to view
Ø Passes data from controller to respective view
Ø Their value becomes null when any redirection occurs, because their role is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.
3. What are the differences between ViewData and ViewBag?
Ø ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
Ø ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
Ø ViewData requires typecasting for complex data type and checks for null values to avoid error.
Ø ViewBag doesn’t require typecasting for complex data type.
NOTE: Although there might not be a technical advantage to choosing one format over the other, there are some critical differences to be aware of between the two syntaxes.
One obvious difference is that ViewBag works only when the key being accessed is a valid C# identifier. For example, if you place a value in ViewData["KeyWith Spaces"], you can’t access that value using ViewBag because the code won’t compile.
Another key issue to be aware of is that dynamic values cannot be passed in as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order for it to choose the correct extension method.
If any parameter is dynamic, compilation will fail. For example, this code will always fail: @Html.TextBox("name", ViewBag.Name). To work around this, either use ViewData["Name"] or cast the value to a specific type: (string) ViewBag.Name.
4. What is TempData?
TempData is a dictionary derived from the TempDataDictionary class and stored in short lives session. It is a string key and object value.
It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain data when we move from one controller to another controller or from one action to other action. In other words, when we redirect Tempdata helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is used when we are sure that the next request will be redirecting to next view. It requires typecasting for complex data type and checks for null values to avoid error. Generally it is used to store only one time messages like error messages, validation messages.
5. How can you define a dynamic property with the help of viewbag in ASP.NET MVC?
Assign a key name with syntax, ViewBag.[Key]=[ Value] and value using equal to operator.
For example, you need to assign list of students to the dynamic Students property of ViewBag.
6. What is ViewModel?
Accepted a view model represents data that you want to have displayed on your view/page.
Let's say that you have an Employee class that represents your employee domain model and it contains the following 4 properties:
View models differ from domain models in that view models only contain the data (represented by properties) that you want to use on your view. For example, let's say that you want to add a new employee record, your view model might look like this:
As you can see, it only contains 2 of the properties of the employee domain model. Why is this you may ask? Id might not be set from the view, it might be auto generated by the Employee table. AndDateCreated might also be set in the stored procedure or in the service layer of your application. So Id and DateCreated is not needed in the view model.
When loading the view/page, the create action method in your employee controller will create an instance of this view model, populate any fields if required, and then pass this view model to the view:
Your view might look like this (assuming you are using ASP.NET MVC3 and razor):
Validation would thus be done only on FirstName and LastName. Using Fluent Validation, you might have validation like this:
The key thing to remember is that the view model only represents the data that you want use. You can imagine all the unnecessary code and validation if you have a domain model with 30 properties and you only want to update a single value. Given this scenario, you would only have this one value/property in the view model and not the whole domain object.
7. What are Scaffold templates?
These templates use the Visual Studio T4 templating system to generate a view based on the model type selected. Scaffolding in ASP.NET MVC can generate the boilerplate code we need for create, read, update, and delete (CRUD) functionality in an application. The scaffolding templates can examine the type definition for, and then generate a controller and the controller’s associated views. The scaffolding knows how to name controllers, how to name views, and what code needs to go in each component, and where to place all these pieces in the project for the application to work.
8. What are the types of Scaffolding Templates?
Various types are as follows:
9. Show an example of difference in syntax in Razor and WebForm View?
Code expressions in Razor are always HTML encoded. This Web Forms syntax also automatically HTML encodes the value.
10. What are Code Blocks in Views?
Unlike code expressions, which are evaluated and output to the response, blocks of code are simply sections of code that are executed. They are useful for declaring variables that we may need to use later.
11. What is HelperPage.IsAjax Property?
HelperPage.IsAjax gets a value that indicates whether Ajax is being used during the request of the Web page.
Ø Namespace: System.Web.WebPages
Ø Assembly: System.Web.WebPages.dll
However, the same can be achieved by checking requests header directly:
12. Explain combining text and markup in Views with the help of an example?
This example shows what intermixing text and markup looks like using Razor as compared to Web Forms:
14. Explain Routing in MVC?
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.
Routing within the ASP.NET MVC framework serves two main purposes:
Ø It matches incoming requests that would not otherwise match a file on the file system and maps the requests to a controller action.
Ø It constructs outgoing URLs that correspond to controller actions.
15. How route table is created in ASP.NET MVC?
When an MVC application first starts, the Application_Start() method in global.asax is called. This method calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table for MVC application.
16. What are Layouts in ASP.NET MVC Razor?
Layouts in Razor help maintain a consistent look and feel across multiple views within our application. As compared to Web Forms, layouts serve the same purpose as master pages, but offer both a simpler syntax and greater flexibility.
We can use a layout to define a common template for your site (or just part of it). This template contains one or more placeholders that the other views in your application provide content for. In some ways, it’s like an abstract base class for your views.
E.g. declared at the top of view as:
17. What is ViewStart?
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 file 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 file in the Views directory. It specifies a default layout:
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.
18. What are HTML Helpers?
HTML helpers are methods we can invoke on the HTML property of a view. We also have access to URL helpers (via the Url property), and AJAX helpers (via the Ajax property). All these helpers have the same goal: to make views easy to author. The URL helper is also available from within the controller. Most of the helpers, particularly the HTML helpers, output HTML markup. For example, the BeginForm helper is a helper we can use to build a robust form tag for our search form, but without using lines and lines of code:
19. What is Html.ValidationSummary?
The ValidationSummary helper displays an unordered list of all validation errors in the ModelState dictionary. The Boolean parameter you are using (with a value of true) is telling the helper to exclude property-level errors. In other words, you are telling the summary to display only the errors in ModelState associated with the model itself, and exclude any errors associated with a specific model property. We will be displaying property-level errors separately. Assume you have the following code somewhere in the controller action rendering the edit view:
The first error is a model-level error, because you didn’t provide a key (or provided an empty key) to associate the error with a specific property. The second error you associated with the Title property, so in your view it will not display in the validation summary area (unless you remove the parameter to the helper method, or change the value to false). In this scenario, the helper renders the following HTML:
Other overloads of the ValidationSummary helper enable you to provide header text and set specific HTML attributes.
NOTE: By convention, the ValidationSummary helper renders the CSS class validation-summary-errors along with any specific CSS classes you provide. The default MVC project template includes some styling to display these items in red, which you can change in styles.css.
20. What are Validation Annotations?
Data annotations are attributes you can find in System.ComponentModel.DataAnnotations namespace. These attributes provide server-side validation, and the framework also supports client-side validation when you use one of the attributes on a model property. You can use four attributes in the DataAnnotations namespace to cover common validation scenarios,
Required, String Length, Regular Expression, Range.
21. What is Html.Partial?
The Partial helper renders a partial view into a string. Typically, a partial view contains reusable markup you want to render from inside multiple different views. Partial has four overloads:
22. What is Html.RenderPartial?
The RenderPartial helper is similar to Partial, but RenderPartial writes directly to the response output stream instead of returning a string. For this reason, you must place RenderPartial inside a code block instead of a code expression. To illustrate, the following two lines of code render the same output to the output stream:
23. If they are the same, then which one to use?
In general, you should prefer Partial to RenderPartial because Partial is more convenient (you don’t have to wrap the call in a code block with curly braces). However, RenderPartial may result in better performance because it writes directly to the response stream, although it would require a lot of use (either high site traffic or repeated calls in a loop) before the difference would be noticeable.
24. How do you return a partial view from controller?
25. What are different ways of returning a View?
There are different ways for returning/rendering a view in MVC Razor. E.g. return View(), return RedirectToAction(), return Redirect() and return RedirectToRoute().
26. How do you check for AJAX request with C# in MVC.NET?
The solution is independent of MVC.NET framework and is global across server side technologies. Most modern AJAX applications utilize XmlHTTPRequest to send async request to the server. Such requests will have distinct request header: