We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Sunday, March 22, 2015

Interview questions and answers in MVC

1. What is MVC?


MVC stands for Model-View-Controller. It is a software design pattern that was introduced in the 1970s. Also, the MVC pattern forces a separation of concerns, it means domain model and controller logic are decoupled from the user interface (view). As a result maintenance and testing of the application become simpler and easier.

2. Explain the MVC design pattern?

MVC design pattern splits an application into three main aspects: Model, View, and Controller.
a. Model - The Model represents a set of classes that describe the business logic i.e. business model as well as data access operations i.e. data model. It also defines business rules for data means how the data can be changed and manipulated.
b. View - The View represents the UI components like CSS, jQuery, Html, etc. It is only responsible for displaying the data that is received from the controller as a result. This also transforms the model(s) into UI.
c. Controller - The Controller is responsible to process incoming requests. It receives input from users via the View, then processes the user's data with the help of Model and passing the results back to the View. Typically, it acts as the coordinator between the View and the Model.
Today, this pattern is used by many popular frameworks like Ruby on Rails, Spring Framework, Apple iOS Development, and ASP.NET MVC.

3. What is Domain Driven Design and Development?

Domain-Driven Design (DDD) is a collection of principles and patterns that help developers to make design decisions to develop elegant systems for different domains. It is not a technology or methodology.
The main components of DDD are Entity, Value Object, Aggregate, Service, and Repository.
i. Entity- An object that has an identity- it is unique within the system, like Customer, Employee, etc.
ii. Value Object- An object that has no identity within the system like Rate, State, etc.
iii. Note- A value object can become an entity depending on the situation.
iv. Aggregate- An aggregate root is a special kind of entity that consumers refer to directly. All consumers of the aggregate root are called aggregate. The aggregate root guarantees the consistency of changes being made within the aggregate.
v.Service- A service is a way of dealing with actions, operations, and activities within your application.
vi. Repository- A repository is responsible to store and to retrieve your data. It is not a concern of how and where data will persist. So, it can be SQL server, oracle, XML, text file or anything else. The repository is not a Data Access Layer but it refers to a location for storage, often for safety or preservation.

4. What is the MVP pattern?

This pattern is similar to the MVC pattern in which the controller has been replaced by the presenter. This design pattern splits an application into three main aspects: Model, View, and Presenter.
i. Model - The Model represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.
ii. View - The View represents the UI components like CSS, jQuery, Html, etc. It is only responsible for displaying the data that is received from the presenter as a result. This also transforms the model(s) into UI.
iii. Presenter - The Presenter is responsible for handling all UI events on behalf of the view. This receives input from users via the View, then process the user's data with the help of Model and passing the results back to the View. Unlike view and controller, view and presenter are completely decoupled from each other’s and communicate with each other by an interface.
Also, the presenter does not manage the incoming request traffic as a controller.
This pattern is commonly used with ASP.NET Web Forms applications which require to create automated unit tests for their code-behind pages. This is also used with windows forms.

5. Key Points about MVP Pattern

01. The user interacts with the View.
02. There is a one-to-one relationship between View and Presenter means one View is mapped to only one Presenter.
03. The view has a reference to Presenter but View has not to reference to Model.
04. It provides two-way communication between View and Presenter.

6. What is the MVVM pattern?

MVVM stands for Model-View-View Model. This pattern supports two-way data binding between view and View model. This enables automatic propagation of changes, within the state of view model to the View. Typically, the view model uses the observer pattern to notify changes in the view model to model.
01. Model - The Model represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.
02.View - The View represents the UI components like CSS, jQuery, Html, etc. It is only responsible for displaying the data that is received from the controller as a result. This also transforms the model(s) into UI.
03.View Model - The View Model is responsible for exposing methods, commands, and other properties that help to maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events in the view itself.
This pattern is commonly used by the WPF, Silverlight, Caliburn, route, etc.

7. Key Points about MVVM Pattern

i. The user interacts with the View.
ii. There is a many-to-one relationship between View and ViewModel means many View can be mapped to one ViewModel.
iii. A view has a reference to ViewModel but View Model has no information about the View.
iv. Supports two-way data binding between View and ViewModel.

8. What is ASP.NET MVC?

ASP.NET MVC is an open-source framework built on the top of the Microsoft .NET Framework to develop a web application that enables a clean separation of code. ASP.NET MVC framework is the most customizable and extensible platform shipped by Microsoft.

9. What are the advantages of ASP.NET MVC?

There are following advantages of ASP.NET MVC over Web Forms (ASP.NET):
01.Separation of concern - MVC design pattern divides the ASP.NET MVC application into three main aspects Model, View, and Controller which make it easier to manage the application complexity.
02.TDD - The MVC framework brings better support to test-driven development.
03.Extensible and pluggable - MVC framework components were designed to be pluggable and extensible and therefore can be replaced or customized easier then WebForms.
04. Full control over application behavior - MVC framework doesn’t use View State or server-based forms like WebForms. This gives the application developer more control over the behaviors of the application and also reduces the bandwidth of requests to the server.
05.ASP.NET features are supported - MVC framework is built on top of ASP.NET and therefore can use most of the features that ASP.NET includes such as the provider's architecture, authentication, and authorization scenarios, membership, and roles, caching, session and more.
06.URL routing mechanism - MVC framework supports a powerful URL routing mechanism that helps to build a more comprehensible and searchable URL in your application. This mechanism helps the application to be more addressable from the eyes of search engines and clients and can help in search engine optimization.

10. Explain the evolution history of ASP.NET MVC?

Here is the list of the released version history of ASP.NET MVC Framework with their features.
ASP.NET MVC1
1.Released on Mar 13, 2009
2.Runs on .NET 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1
3.MVC Pattern architecture with WebForm Engine
4.Html Helpers
5.Ajax helpers
6.Routing
7.Unit Testing
ASP.NET MVC2
1.Released on Mar 10, 2010
2.Runs on .NET 3.5, 4.0 and with Visual Studio 2008 & 2010
3.Strongly typed HTML helpers means lambda expression based Html Helpers
4.Templated Helpers
5.UI helpers with automatic scaffolding & customizable templates
6.Support for DataAnnotations Attributes to apply model validation on both client and server sides.
7.Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE ? Areas for partitioning large applications into modules
8.Asynchronous controllers
ASP.NET MVC3
1.Released on Jan 13, 2011
2.Runs on .NET 4.0 and with Visual Studio 2010
3.The Razor view engine
4.Enhanced Data Annotations attributes for model validation on both client and server sides
5.Remote Validation
6.Compare Attribute
7.Session less Controller
8.Child Action Output Caching
9.Dependency Resolver
10.Entity Framework Code First support
11.Partial-page output caching
12.ViewBag dynamic property for passing data from controller to view
13.Global Action Filters
14.Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
15.Use of NuGet to deliver software and manage dependencies throughout the platform
ASP.NET MVC4
1.Released on Aug 15, 2012
2.Runs on .NET 4.0, 4.5 and with Visual Studio 2010SP1 & Visual Studio 2012
3.ASP.NET WEB API
4.Enhancements to default project templates
5.Mobile project template using jQuery Mobile
6.Display Modes
7.Task support for Asynchronous Controllers
8.Bundling and minification
9.Support for the Windows Azure SDK
ASP.NET MVC5
1.Released on 17 October 2013
2.Runs on .NET 4.5, 4.5.1 and with Visual Studio 2012 & Visual Studio 2013
3.One ASP.NET
4.ASP.NET Identity
5.ASP.NET Scaffolding
6.Authentication filters - run prior to authorization filters in the ASP.NET MVC pipeline
7.Bootstrap in the MVC template
8.ASP.NET WEB API2

11.What is the difference between 3-layer architecture and MVC architecture?

The 3-layer architecture separates the application into 3 components which consist of Presentation Layer Business Layer and Data Access Layer. In 3-layer architecture, the user interacts with the Presentation layer. 3-layer is a linear architecture.
MVC architecture separates the application into three components which consist of Model, View, and Controller. In MVC architecture, the user interacts with the controller with the help of view. MVC is a triangle architecture
MVC does not replace 3-layer architecture. Typically 3-layer and MVC are used together and MVC acts as the Presentation layer.

12. What is the difference between ASP.NET WebForm and ASP.NET MVC?

Asp.Net Web Forms:-
Asp.Net Web Form follows a traditional event-driven development model.
Asp.Net Web Form has server controls.
Asp.Net Web Form supports view state for state management at the client-side.
Asp.Net Web Form has file-based URLs means file name exists in the URLs must have its physical existence.
Asp.Net Web Form follows Web Forms Syntax
In Asp.Net Web Form, Web Forms(ASPX) i.e. views are tightly coupled to Code behind(ASPX.CS) i.e. logic.
Asp.Net Web Form has Master Pages for a consistent look and feels.
Asp.Net Web Form has User Controls for code re-usability.
Asp.Net Web Form is not Open Source.
Asp.Net Web Form has built-in data controls and best for rapid development with powerful data access.
Asp.Net MVC:-
Asp.Net MVC is a lightweight and follows MVC (Model, View, Controller) pattern-based development, model.
Asp.Net MVC has Html helpers.
Asp.Net MVC does not support the view state.
Asp.Net MVC has route-based URLs mean URLs are divided into controllers and actions and moreover it is based on controller not on physical file.
Asp.Net MVC follow customizable syntax (Razor as default)
In Asp.Net MVC, Views and logic are kept separately.
Asp.Net MVC has Layouts for a consistent look and feels.
Asp.Net MVC has Partial Views for code re-usability.
Asp.Net MVC is lightweight, provides full control over markup and supports many features that allow fast & agile development. Hence it is best for developing an interactive web application with the latest web standards.
Asp.Net Web MVC is an Open Source.

13.Asp.Net Web API VS Asp.Net MVC

01.
Asp.Net MVC is used to create web applications that return both views and data but Asp.Net Web API is used to create full-blown HTTP services with an easy and simple way that returns only data, not view.
02.
Web API helps to build REST-ful services over the .NET Framework and it also supports content-negotiation(it's about deciding the best response format data that could be acceptable by the client. it could be JSON, XML, ATOM or other formatted data), self-hosting which are not in MVC.
03.
Web API also takes care of returning data in a particular format like JSON, XML or any other based upon the Accept header in the request and you don't worry about that. MVC only returns data in JSON format using JsonResult.
04.
In Web API the request is mapped to the actions based on HTTP verbs but in MVC it is mapped to the action name.
05.
Asp.Net Web API is a new framework and part of the core ASP.NET framework. The model binding, filters, routing, and other MVC features exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these features exist within System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand-alone service layer.
06.
You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML or any other format and building a full-blown HTTP service. Typically, this will be called Web API self-hosting.
07.
When you have mixed MVC and Web API controller and you want to implement the authorization then you have to create two filters one for MVC and another for Web API since both are different.
08.
Moreover, Web API is lightweight architecture and except for the web application, it can also be used with smartphone apps.

14.Explain Example of Required Validation in MVC

private class Person
{
[Required]
public string FirstName { get; set; }

[Required]
public string LastName { get; set; }

public bool Married { get; set; }

[RequiredIfTrue("Married")]
public string MaidenName { get; set; }
}

15. What are HTML Helpers in ASP.NET MVC?

Think of HTML Helper in ASP.NET MVC as a method returning a string. So, What can be that string? The returning string is basically an HTML string that can render an HTML tag, For example, a link, an image or other form elements.
Developers who have worked with ASP.NET Web Forms can map HTML helper to Web Form Controls because both serve the same purpose. But HTML helper is comparatively lightweight because they don’t have view state and event models like Web Form Controls. Along with the built-in HTML helpers, we can also create our own custom helpers to fulfill our specific needs.

16. What Standard HTML Helpers renders?

For ASP.NET MVC Developers, understanding of standard HTML Helpers is highly desirable. Standard HTML Helpers can be categorized as follows:
URL Helpers
HTML Links
Image Links
HTML Form Elements

17.MVC URL Helpers

Rendering a link in HTML is a very common requirement. There are two different types of URL Helpers available in ASP.NET MVC i.e. for HTML Links and Image Links. Let’s discuss both of them one by one.
1. HTML Links
Html.ActionLink() helper is used to render an HTML link in a View. ActionLink() method actually links to a Controller action from inside a View.

@Html.ActionLink(“Web Development Tutorial Company Profile”, “CompanyInfo”)
The above line of code is an example of Html.ActionLink() method that renders an HTML anchor tag and linking to a Controller action “CompanyInfo” in a View as follows:
Web Development Tutorial Company Profile
2. Image Links
In order to generate an Image Link, Url.Action() helper is available.

19: If there is no match in the routeing table for the incoming request's URL, which error will result?

404 HTTP status code

20: How to enable Attribute Routing?

By adding a Routes.MapMvcAttributeRoutes() method to the RegisterRoutes() method of the RouteConfig.cs file.
I think 20 questions are enough for one day.

21. Can we remove the default View Engine?

Yes, by using the following code:
protected void Application_Start()
{
ViewEngines.Engines.Clear();
}

22. Can we have a Custom View Engine?

Yes, by implementing the IViewEngine interface or by inheriting from the VirtualPathProviderViewEngine abstract class.

23. Can we use a third-party View Engine?

Yes, ASP.NET MVC can have Spark, NHaml, NDjango, Hasic, Brail, Bellevue, Sharp Tiles, String Template, Wing Beats, SharpDOM and so on third-party View Engine.

24. What is the View Engines?

View Engines are responsible for rendering the HTML from your views to the browser.

25. What is Razor Engine?

The Razor view engine is an advanced view engine from Microsoft, packaged with MVC 3. Razor uses an @ character instead of aspx's <% %> and Razor does not require you to explicitly close the code-block.

26. What is scaffolding?

Quickly generating a basic outline of your software that you can then edit and customize.

27. What is the name of Nuget scaffolding package for ASP.NET MVC3 scaffolding?

MvcScaffolding

28. Can we share a view across multiple controllers?

Yes, it is possible to share a view across multiple controllers by putting a view into the shared folder.

29. What is unit testing?

The testing of every smallest testable block of code in an automated manner. Automation makes things more accurate, faster and reusable.

30. Is unit testing of MVC application possible without running the controller?

Yes, by the preceding definition.

31. Can you change the action method name?

Yes, we can change the action method name using the ActionName attribute. Now the action method will be called by the name defined by the ActionName attribute.
[ActionName("DoAction")]
public ActionResult DoSomething()
{
/TODO:
return View();
}

32. How to prevent a controller method from being accessed by an URL?

By making the method private or protected but sometimes we need to keep this method public. This is where the NonAction attribute is relevant.

33. What are the features of MVC5?

Scaffolding
ASP.NET Identity
One ASP.NET
Bootstrap
Attribute Routing
Filter Overrides

34. What are the various types of filters in an ASP.NET MVC application?

Authorization filters
Action filters
Result filters
Exception filters

35. How do you return a partial view from the controller?

return PartialView(options); //options could be Model or View name

36. What are various ways of returning a View?

There are various ways for returning/rendering a view in MVC Razor. For example "return View()", "return RedirectToAction()", "return Redirect()" and "return RedirectToRoute()".

37.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, we 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 ")

38. What are Validation Annotations?

Data annotations are attributes we can find in the "System.ComponentModel.DataAnnotations" namespace. These attributes provide server-side validation, and the framework also supports client-side validation when we use one of the attributes on a model property. We can use four attributes in the DataAnnotations namespace to cover the common validation scenarios, Required, String Length, Regular Expression, and Range.

39. What is Html.Partial?

The Partial helper renders a partial view into a string. Typically, a partial view contains reusable markup we 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);

40. What is Html.ValidationSummary?

The ValidationSummary helper displays an unordered list of all validation errors in the ModelState dictionary. The Boolean parameter we are using (with a value of true) is telling the helper to exclude property-level errors. In other words, we 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 we 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 we didn't provide a key (or provided an empty key) to associate the error with a specific property. The second error we associated with the Title property, so in our view, it will not display in the validation summary area (unless we remove the parameter to the helper method, or change the value to false). In this scenario, the helper renders the following HTML:


  • This is all wrong!

Other overloads of the ValidationSummary helper enable us to provide header text and set specific HTML attributes.

41. 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)) {


}

42. What is ViewStart?

For a 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 as in the following:

@{
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 then 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 then the view can set those values to another value.

43. How is a routeing table 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 the MVC application.

44. What are Layouts in ASP.NET MVC Razor?

Layouts in Razor help maintain a consistent look and feel across multiple views within our application. 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 our site (or just part of it). This template contains one or more placeholders that the other views in our application provide content for. In some ways, it's like an abstract base class for our views. For example, declared at the top of view as in the following:
@{
Layout = "~/Views/Shared/SiteLayout.cshtml";
}

45. How can you call a JavaScript function/method on the change of a Dropdown List in MVC?

Create a JavaScript method:

Invoke the method:

<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Users, "Value", "Text"),
"Please Select a User", new { id = "ddlUsers",
onchange="selectedIndexChanged()" })%>

46. 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. A Routing module is responsible for mapping incoming browser requests to specific MVC controller actions.

Routing within the ASP.NET MVC framework serves the following 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.

47.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 the business logic layer, it may result in redundant code for accessing data for similar entities or it may result in code that is hard to test or understand. To overcome these kinds of issues, and to write interface driven and test-driven code to access data, we use the Repository Pattern. The repository makes queries to the data source for the data then maps the data from the data source to a business entity/domain object and finally 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 the following 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 a Repository, we write our entire business logic of CRUD operations using Entity Framework classes that will not only result in meaningful test-driven code but will also reduce our controller code of accessing data.

48. What is Code Blocks in Views?

Unlike code expressions that are evaluated and sent 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."; %>

49. 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 to create, read, update, and delete (CRUD) functionality in an application. The scaffolding templates can examine the type definition for it then generate a controller and the controller's associated views. The scaffolding knows how to name controllers, how to name views, what code needs to go to each component, and where to place all these pieces in the project for the application to work.

50. What are the types of Scaffolding Templates?

Empty: Creates an 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.
It 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.
It generates a label and input field for each property of the model type.
List: Creates a view with a table of model instances. It generates a column for each property of the model type. Make sure to pass an IEnumerable to this view from our action method.
The view also contains links to actions for performing the create/edit/delete operations.

51. What is Routing in ASP.NET MVC?

In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx file. On the other hand, ASP.NET MVC framework uses friendly URLs that more easily describe user’s action but not mapped to physical files. Let’s see below URLs for both ASP.NET and ASP.NET MVC.

//ASP.NET approach – Pointing to physical files (Student.aspx)
//Displaying all students
http://locahost:XXXX/Student.aspx

//Displaying a student by Id = 5
http://locahost:XXXX/Student.aspx?Id=5


//ASP.NET MVC approach – Pointing to Controller i.e. Student
//Displaying all students
http://locahost:XXXX/Student

//Displaying student by Id = 5
http://locahost:XXXX/Student/5/
ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define routing rules for the engine, so that it can map incoming request URLs to the appropriate controller. Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses the “go” button, the routing engine uses routing rules that are defined in Global.asax file in order to parse the URL and find out the path of the corresponding controller.

52. What is the difference between ViewData, ViewBag, and TempData?

In order to pass data from controller to view and in the next subsequent request, ASP.NET MVC framework provides different options i.e. ViewData, ViewBag, and TempData.

Both ViewBag and ViewData are used to communicate between the controller and the corresponding view. But this communication is only for server call, it becomes null if a redirect occurs. So, in short, its a mechanism to maintain state between the controller and corresponding view. ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn’t have typecasting and null checks.

TempData is also a dictionary object that stays for the time of an HTTP Request. So, Temp data can be used to maintain data between redirects i.e from one controller to the other controller.

53. What are Action Filters in ASP.NET MVC?

If we need to apply some specific logic before or after action methods, we use action filters. We can apply these action filters to a controller or a specific controller action. Action filters are basically custom classes that provide a mean for adding pre-action or post-action behavior to controller actions.
For example,

Authorize filter can be used to restrict access to a specific user or a role.
OutputCache filter can cache the output of a controller action for a specific duration.

54. What is Web API ‘s in Asp.Net MVC ?

Web API is a new framework for consuming & building HTTP Services.
Web API supports a wide range of clients including different browsers and mobile devices.
It is a very good platform for developing RESTful services since it talk’s about HTTP.

55. What is the use of web API ? Why Web API needed If you have already RESTful services using WCF ?

Yes, we can still develop the RESTful services with WCF, but there are two main reasons that prompt users to use Web API instead of RESTful services.

ASP.NET Web API is included in ASP.NET MVC which obviously increases TDD (Test Data Driven) approach in the development of RESTful services.
For developing RESTful services in WCF you still need a lot of config settings, URI templates, contract’s & endpoints which developing RESTful services using web API is simple.

59. What are the new enhancements done in the default project template of ASP.NET MVC?

Adaptive rendering for Nice Look & Feel
Modern Looking for Mobile & Desktop browser
The new enhanced default project template came up with modern looking. Along with some cosmetic enhancements, it also employs new adaptive rendering to look nice in both desktop and mobile browsers without the need for any kind of additional customization.

60. Why we need a separate mobile project template, while we can render our web application in mobile (What’s new in MVC 4 Mobile template)?

Smart Phones & tablets touch got smart by using new jQuery.Mobile.MVC NuGet package.
The mobile project template touch optimized UI by using jQuery.Mobile.MVC NuGet Package for tablets and smart phones.

61. What is the use of Display Modes?

The view can be changed automatically based on browser(For mobile and desktop browsers)
Display Modes is a newly added feature in ASP.NET MVC 4. Views selected automatically by application depending on the browser. Example: If a desktop browser requests a login page of an application it will return Views\Account\Login.cshtml view & if a mobile browser requests the home page it will return Views\Account\Login.mobile.cshtml view.

62. What are the main features of ASP.NET MVC 4 used by ASP.NET Web API?

Routing changes: ASP.NET Web API uses same convention for config mapping that ASP.NET MVC provides.
Model Binding & Validation: ASP.NET Web API uses the same model binding functionality, but HTTP specific context related operations only.
Filters: The ASP.NET Web API uses most of built-in filters from MVC.
Unit Testing: Now Unit testing based on MVC, strongly unit testable.

63. What are Bundling & Minification features in ASP.NET MVC 4?

Bundling & Minification reduce number of HTTP requests. Bundling & Minification combines individual files into single. Bundled file for CSS & scripts and then it reduces overall size by minifying the contents of the bundle.

64. What is the difference between asynchronous controller implementation b/w ASP.NET MVC 3 & ASP.NET MVC 4? Can you explain in detail?

There is a major difference is on the implementation mechanism between ASP.NET MVC 3 and ASP.NET MVC 4.

In ASP.NET MVC 3, to implement async controller or methods we need to derive controller from AsyncController rather than from normal plain Controller class. We need to create 2 action methods rather than one. First with suffix ‘Async’ keyword & second with ‘Completed’ suffix.
In ASP.NET MVC 4 you need not declare 2 action methods. One can serve the purpose. MVC 4 using .Net Framework 4.5 support for asynchronous communication.

65. Is MVC 4 supporting Windows Azure SDK (Software Development Kit) ?

Yes, MVC 4 is supporting Windows Azure SDK version 1.6 or higher.

66. What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”?

Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t. Below is a simple HTML code that just creates a simple textbox with “CustomerCode” as name.

Html.TextBox("CustomerCode")
Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘CustomerCode” from object “m”.

Html.TextBoxFor(m => m.CustomerCode)
In the same way we have for other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.

67.Explain attribute based routing in MVC?

This is a feature introduced in MVC 5. By using the "Route" attribute we can define the URL structure. For example in the below code we have decorated the "GotoAbout" action with the route attribute. The route attribute says that the "GotoAbout" can be invoked using the URL structure "Users/about".

public class HomeController : Controller
{
[Route("Users/about")]
public ActionResult GotoAbout()
{
return View();
}
}

68. How can we navigate from one view to another using a hyperlink?

By using the ActionLink method as shown in the below code. The below code will create a simple URL that helps to navigate to the “Home” controller and invoke the GotoHome action.
<%= Html.ActionLink("Home","Gotohome") %>

69. How can we restrict MVC actions to be invoked only by GET or POST?

We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls. For instance we can see in the below code snippet the DisplayCustomer action can only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an error.

Hide Copy Code
[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}

70. How can we maintain sessions in MVC?

Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.

71. Does “TempData” preserve data in the next request also?

“TempData” is available through out for the current request and in the subsequent request, it’s available depending on whether “TempData” is read or not.

So if “TempData” is once read it will not be available in the subsequent request.

72. What is the use of Keep and Peek in “TempData”?

Once “TempData” is read in the current request it’s not available in the subsequent request. If we want “TempData” to be read and also available in the subsequent request then after reading we need to call “Keep” method as shown in the code below.

@TempData[“MyData”];
TempData.Keep(“MyData”);
The more shortcut way of achieving the same is by using “Peek”. This function helps to read as well advices MVC to maintain “TempData” for the subsequent request.

string str = TempData.Peek("Td").ToString();

73. How can we do validations in MVC?

One of the easiest ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes that can be applied to model properties. For example, in the below code snippet we have a simple Customer class with a property customercode.

This customer code property is tagged with a Required data annotation attribute. In other words, if this model is not provided customer code, it will not accept it.

public class Customer
{
[Required(ErrorMessage="Customer code is required")]
public string CustomerCode
{
set;
get;
}
}
In order to display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post)) { %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>

<%}%>
Later in the controller, we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take action.

Hide Copy Code
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Customer");
}
}

74.Can we display all errors in one go?

Yes, we can; use the ValidationSummary method from the Html helper class.

<%= Html.ValidationSummary() %>

75. What are the other data annotation attributes for validation in MVC?

If we want to check string length, we can use StringLength.

[StringLength(160)]
public string FirstName { get; set; }
In case we want to use a regular expression, we can use the RegularExpression attribute.

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }
If we want to check whether the numbers are in range, we can use the Range attribute.

[Range(10,25)]
public int Age { get; set; }
Sometimes we would like to compare the value of one field with another field, we can use the Compare attribute.

public string Password { get; set; }
[Compare("Password")]
public string ConfirmPass { get; set; }
In case we want to get a particular error message , we can use the Errors collection.

var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;
If we have created the model object yourself you can explicitly call TryUpdateModel in your controller to check if the object is valid or not.

TryUpdateModel(NewCustomer);
In case we want add errors in the controller we can use the AddModelError function.

ModelState.AddModelError("FirstName", "This is my server-side error.");

76. How can we enable data annotation validation on client side?

It’s a two-step process: first reference the necessary jQuery files.




The second step is to call the EnableClientValidation method.

<% Html.EnableClientValidation(); %>

77. Why Razor when we already have ASPX?

Razor is clean, lightweight, and syntaxes are easy as compared to ASPX. For example, in ASPX to display simple time, we need to write:

<%=DateTime.Now%>
In Razor, it’s just one line of code:

@DateTime.Now

78. How can you do authentication and authorization in MVC?

We can use Windows or Forms authentication for MVC.

79. How do you implement Forms authentication in MVC?

Forms authentication is implemented the same way as in ASP.NET. The first step is to set the authentication mode equal to Forms. The loginUrl points to a controller here rather than a page.




We also need to create a controller where we will check if the user is proper or not. If the user is proper we will set the cookie value.

public ActionResult Login()
{
if ((Request.Form["txtUserName"] == "mks") &&
(Request.Form["txtPassword"] == "mks@123"))
{
FormsAuthentication.SetAuthCookie("mks",true);
return View("About");
}
else
{
return View("Index");
}
}
All the other actions need to be attributed with the Authorize attribute so that any unauthorized user making a call to these controllers will be redirected to the controller (in this case the controller is “Login”) which will do the authentication.

[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}

80. What is the difference between ActionResult and ViewResult?

ActionResult is an abstract class while ViewResult derives from the ActionResult class. ActionResult has several derived classes like ViewResult, JsonResult, FileStreamResult, and so on.
ActionResult can be used to exploit polymorphism and dynamism. So if we are returning different types of views dynamically, ActionResult is the best thing. For example in the below code snippet, we can see we have a simple action called DynamicView. Depending on the flag (IsHtmlView) it will either return a ViewResult or JsonResult.
public ActionResult DynamicView()
{
if (IsHtmlView)
return View(); // returns simple ViewResult
else
return Json(); // returns JsonResult view
}

No comments: