Search This Blog

Thursday, December 5, 2013

MVC Interview Questions and Answers Part 2

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.
List<string> students = new List<string>();
students.Add("aa");
students.Add("bb");
ViewBag.Students = students;
//Students is a dynamic property associated with 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:
public class Employee : IEntity
{
     public int Id { get; set; }  // Employee's unique identifier
     public string FirstName { get; set; }  // Employee's first name
     public string LastName { get; set; }  // Employee's last name
     public DateTime DateCreated { get; set; }  // Date when employee was created
}
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:
public class CreateEmployeeViewModel
{
     public string FirstName { get; set; }
     public string LastName { get; set; }
}
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:
public class EmployeeController : Controller
{
     private readonly IEmployeeService employeeService;

     public EmployeeController(IEmployeeService employeeService)
     {
          this.employeeService = employeeService;
     }

     public ActionResult Create()
     {
          CreateEmployeeViewModel viewModel = new CreateEmployeeViewModel();

          return View(viewModel);
     }

     public ActionResult Create(CreateEmployeeViewModel viewModel)
     {
          // Do what ever needs to be done before adding the employee to the database
     }
}
Your view might look like this (assuming you are using ASP.NET MVC3 and razor):
@model MyProject.Web.ViewModels.ProductCreateViewModel

<table>
     <tr>
          <td><b>First Name:</b></td>
          <td>@Html.TextBoxFor(x => x.FirstName, new { maxlength = "50", size = "50" })
              @Html.ValidationMessageFor(x => x.FirstName)
          </td>
     </tr>
     <tr>
          <td><b>Last Name:</b></td>
          <td>@Html.TextBoxFor(x => x.LastName, new { maxlength = "50", size = "50" })
              @Html.ValidationMessageFor(x => x.LastName)
          </td>
     </tr>
</table>
Validation would thus be done only on FirstName and LastName. Using Fluent Validation, you might have validation like this:
public class CreateEmployeeViewModelValidator : AbstractValidator<CreateEmployeeViewModel>
{
     public CreateEmployeeViewModelValidator()
     {
          RuleFor(x => x.FirstName)
               .NotEmpty()
               .WithMessage("First name required")
               .Length(1, 50)
               .WithMessage("First name must not be greater than 50 characters");

          RuleFor(x => x.LastName)
               .NotEmpty()
               .WithMessage("Last name required")
               .Length(1, 50)
               .WithMessage("Last name must not be greater than 50 characters");
     }
}
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:
SCAFFOLD           DESCRIPTION

Empty              Creates empty view. Only the model type is specified using the model                 
                   syntax.

Create             Creates a view with a form for creating new instances of the model.
                   Generates a label and input field for each property of the model type.

Delete             Creates a view with a form for deleting existing instances of the
                   model.
                   Displays a label and the current value for each property of the model.

Details            Creates a view that displays a label and the value for each property of
                   The model type.

Edit               Creates a view with a form for editing existing instances of the model.
                   Generates a label and input field for each property of the model type.

List               Creates a view with a table of model instances. Generates a column
                   for each property of the model type. Make sure to pass an
                   IEnumerable<YourModelType> to this view from your action method.
                   The view also contains links to actions for performing the
                   create/edit/delete operation. 

9.      Show an example of difference in syntax in Razor and WebForm View?
Razor:        <span>@model.Message</span>
Web Forms:    <span><%: model.Message %></span>
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.
Razor
@{
int x = 123;
string y = ?because.?;
}
Web Forms
<%
int x = 123;
string y = "because.";
%>

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:
Request["X-Requested-With"] == “XmlHttpRequest”.

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:
Razor
@foreach (var item in items) {
<span>Item @item.Name.</span>
}
Web Forms
<% foreach (var item in items) { %>
<span>Item <%: item.Name %>.</span>
<% } %>

13. How can you call a JavaScript function/method on the change of Dropdown List in MVC?
Create a JavaScript method:
<script type="text/javascript">
function selectedIndexChanged() {
}
</script>
Invoke the method:
<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Users, "Value", "Text"),
"Please Select a User", new { id = "ddlUsers",
onchange="selectedIndexChanged()" })%>

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:
@{
       Layout = "~/Views/Shared/SiteLayout.cshtml";
}

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:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
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:
@using (Html.BeginForm("Search", "Home", FormMethod.Get)) {
<input type="text" name="q" />
<input type="submit" value="Search" />
}




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:
ModelState.AddModelError("", "This is all wrong!");
ModelState.AddModelError("Title", "What a terrible name!");
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:
<div class="validation-summary-errors">
<ul>
<li>This is all wrong!</li>
</ul>
</div>
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:
public void Partial(string partialViewName);
public void Partial(string partialViewName, object model);
public void Partial(string partialViewName, ViewDataDictionary viewData);
public void Partial(string partialViewName, object model,
ViewDataDictionary viewData);

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:
@{Html.RenderPartial("AlbumDisplay "); }
@Html.Partial("AlbumDisplay ")

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?
return PartialView(options); //options could be Model or View name

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:
X-Requested-With = XMLHTTPREQUEST

Popular Posts