Home » » MVC Interview Questions and Module -5

MVC Interview Questions and Module -5

Explain Repository Pattern in ASP.NET MVC?
In simple terms, a repository basically works as a mediator between our business logic layer and our data access layer of the application. Sometimes, it would be troublesome to expose the data access mechanism directly to business logic layer, it may result in redundant code for accessing data for similar entities or it may result in a code that is hard to test or understand. To overcome these kinds of issues, and to write an Interface driven and test driven code to access data, we use Repository Pattern. The repository makes queries to the data source for the data, thereafter maps the data from the data source to a business entity/domain object, finally and persists the changes in the business entity to the data source. According to MSDN, a repository separates the business logic from the interactions with the underlying data source or Web service. The separation between the data and business tiers has three benefits:
·                     It centralizes the data logic or Web service access logic.
·                     It provides a substitution point for the unit tests.
·                     It provides a flexible architecture that can be adapted as the overall design of the application evolves.

In Repository, we write our whole business logic of CRUD operations with the help of Entity Framework classes, that will not only result in meaningful test driven code but will also reduce our controller code of accessing data.

How can you call a javascript function/method on the change of Dropdown List in MVC?
Create a java-script 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()" })%>

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.

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.

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 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";
}

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 fi le 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 fi le in the Views directory. It specifi es 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.

Note: Some of the content has been taken from various books/articles.

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" />
}

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 specifi c 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 specifi c 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.

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.

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);

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 ")

If they are 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.

How do you return a partial view from controller?
return PartialView(options); //options could be Model or View name

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().

0 comments:

Post a Comment