Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Tuesday, 21 March 2017

MVC interview questions Part-8

1. Ques: What is the strongly typed view in ASP.NET MVC? What are the main advantage of using strongly ?
Answer:
The view which bind with any model is called as strogly typed view. You  can bind any class as model to view.You can access model properties on  that view. You can use data associated with model to render controls.
You can bind custom types as well as primitive types like string, array, list etc.

public ActionResult View1()
{
  UserModel obj = new UserModel();
  return view(obj)
}

In view
  @Html.DisplayFor(modelItem => item.TotalWorkHours)

Again Main advantage of using strongly typed view is - You can same  object during posting view. So What ever values assigned to controls  associated models property. You can access in post action

Main advantage of using strongly typed view is -
  • You can use automatic scaffolding 
  • IntelliSense support 
  • Compile time type checking

2. Ques: What are the advantages of weak typing over strong typing?
Answer:
Weak Typing :
  • Requires less programing effort as the compiler or interpreter implicitly performs certain kinds of type conversions. So applications can be built in a rapid manner.
  • Fewer errors are caught at compile time. Many bugs are caught at run-time. Requires more discipline while coding.
Strong Typing:
  • Strong/Static types provide constraints which helps to catch errors during compile time
  • Strong typing provide more opportunities for performance enhancements
  • Strong typed code is easy to understand
  • Limits the developer programming expressiveness.
  • Application development go more slowly.

3. Ques:  What is UpdateModel() in mvc?
Answer:
UpdateModel() is a Controller helper method that attempts to bind a bunch of different input data sources (HTTP POST data coming from a View, QueryString values, Session variables/Cookies, etc.) to the explicit model object you indicate as a parameter.

UpdateModel method to fetch data from view to controller. UpdateModel is the method which is generics type and takes parameter of model type.


Tuesday, 14 March 2017

MVC interview questions Part 7

1. Ques: What is the Entity Framework in .NET ?
Answer:
Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.
                                                               OR

Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.

Entity framework is useful in three scenarios. First, if you already have existing database or you want to design your database ahead of other parts of the application. Second, you want to focus on your domain classes and then create the database from your domain classes. Third, you want to design your database schema on the visual designer and then create the database and classes.

The following figure illustrates the above scenarios.

 Entity Framework overview
As per the above figure, EF creates data access classes for your existing database, so that you can use these classes to interact with the database instead of ADO.Net directly.

EF can also create the database from your domain classes, thus you can focus on your domain-driven design.

EF provides you a model designer where you can design your DB model and then EF creates database and classes based on your DB model.

2. Ques:  Explain the entity framework architecture ?
Answer:
The architecture  of  Entity Framework given bellow . Let discuss  the components of the architecture individually:


Entity Framework Architecture
EDM (Entity Data Model): EDM consists of three main parts - Conceptual model, Mapping and Storage model.

Conceptual Model: The conceptual model contains the model classes and their relationships. This will be independent from your database table design.

Storage Model: Storage model is the database design model which includes tables, views, stored procedures, and their relationships and keys.

Mapping: Mapping consists of information about how the conceptual model is mapped to the storage model.

LINQ to Entities: LINQ to Entities is a query language used to write queries against the object model. It returns entities, which are defined in the conceptual model. You can use your LINQ skills here.

Entity SQL: Entity SQL is another query language just like LINQ to Entities. However, it is a little more difficult than L2E and the developer will have to learn it separately.

Object Service:Object service is a main entry point for accessing data from the database and to return it back. Object service is responsible for materialization, which is the process of converting data returned from an entity client data provider (next layer) to an entity object structure.

Entity Client Data Provider:The main responsibility of this layer is to convert L2E or Entity SQL queries into a SQL query which is understood by the underlying database. It communicates with the ADO.Net data provider which in turn sends or retrieves data from the database.

ADO.Net Data Provider:This layer communicates with the database using standard ADO.Net.


3. Ques: What is an entity in a database ?
Answer:
An entity is any object in the system that we want to model and store information about. Entities are usually recognizable concepts, either concrete or abstract, such as person, places, things, or events which have relevance to the database. Some specific examples of entities are Employee, Student, Lecturer.


4. Ques: How can you enhance the performance of Entity Framework?
Answer:
Following steps should follow, To enhance the performance of Entity Framework

  • Try to avoid to put all the DB objects into one single entity model
  • Disable change tracking for entity if not needed
  • Reduce response time for the first request by using pre-generating Views
  • If not required try to avoid fetching all the fields
  • For data manipulation select appropriate collection
  • Wherever needed use compiled query
  • Avoid using Views and Contains
  • While binding data to grid or paging, retrieve only required no of records
  • Debug and Optimize LINQ query


5. Ques: Explain the code first approach in mvc ? What are the advantages in code first approach ?
Answer:
Entity framework code first approach, we write model classes first and then generates database from the classes.

The Code first approach of the entity framework helps you to develop your application by Domain driven design approach. In domain driven design, developers can focus on core domain and domain logic and can start working with classes as per your domain requirement; no need to create the database first. It is different from data driven programming, in which data controls the business logic and complete application built around the database schema.


Advantage of code first approach:
  • No need to worry about database creation, you can focus on domain logic to solve the business problem
  • Faster coding – you can start coding even if the database is not ready or if you don’t have knowledge about database management.
  • The Code first API of entity framework will automatically create the database and map their relation with model classes.
  • It’s easy to make changes with model classes rather than to databases.
  • No need to edit and update the designer model (.edmx file) in visual studio.

6. Ques: What are new feature in Entity Framework 6 ?
Answer:
Let us take a some of the important features of Entity Framework 6:

Dependency Resolution 
Connection Resiliency
Multiple Contexts per Database
Code Based Configuration
Code First Mapping to Insert/Update/Delete Stored Procedures and many more.


7. Ques: What is the difference between LINQ to SQL and Entity Framework?
Answer:
LINQ to SQL
  • It works only with SQL Server Database
  • To maintain the relation it generates a .dbml
  • It cannot generate database from model
  • It permits one to one mapping between the entity classes and relational views/tables
  • It enables you to query data using DataContext
  • It provides tightly coupled approach
Entity Framework
  • It works with various database like DB2, MYSQL, SQL Server etc.
  • It creates an .edmx files initially and relation is maintained using 3 different files .msl, .csdl and .ssdl
  • It can generate database from model
  • Between the entity classes and relational tables, it permits one-to-one, one-to-many and many-to-many
  • It enables you to query data using EntitySQL, DBContext, and ObjectContext
  • It provides loosely coupled approach

8. Ques: What is Asynchronous controllers in MVC? 
Answer:
The asynchronous controller enables you to write asynchronous action methods. It allows you to perform long running operation(s) without making the running thread idle. 
Asynchronous action methods are useful when an action must perform several independent long running operations. 

Sunday, 12 March 2017

MVC interview questions Part 6

1. Ques: How can we use two (multiple) models with a single view ?
Answer:
10 ways to bind multiple models on a single view given bellow

1. View Model
ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method.

2. View Bag
ViewBag is similar to ViewData and is also used to transfer data from the controller to the view. ViewBag is a dynamic property. ViewBag is just a wrapper around the ViewData.

3. View Data
ViewData is used to transfer data from the controller to the view. ViewData is a dictionary object that may be accessible using a string as the key. Using ViewData, we can pass any object from the controller to the view. The Type Conversion code is required when enumerating in the view.

4. Temp Data
TempData is also a dictionary derivative from TempDataDictionary class. TempData stored in short lives session. We can pass multiple models through TempData also.

5. Session
Session is used to pass data across controllers in MVC Application.Session data never expires (by default session expiration time is 20 minutes but it can be increased).Session is valid for all requests, not for a single redirect.

6. Dynamic Model
ExpandoObject (the System.Dynamic namespace) is a class that was added to the .Net Framework 4.0 that allows us to dynamically add and remove properties onto an object at runtime.

7. Tuples
A Tuple object is an immutable, fixed-size and ordered sequence object. It is a data structure that has a specific number and sequence of elements. The .NET framework supports tuples up to seven elements.

8. Render Action
A Partial View defines or renders a partial view within a view. We can render some part of a view by calling a controller action method using the Html.RenderAction method. The RenderAction method is very useful when we want to display data in the partial view. The disadvantages of this method is that there are only multiple calls of the controller.

9. JSON
We can Bind Multiple Models with the help of Json as well. We will retun JsonResult from action Method and on View through JQuery we can pasrse the JSON data and Bind on View.

10. Navigation Properties
If we have two related models then we can bind a model into another model as a property and can pass to a View.


2. Ques: What is csrf(Cross-Site Request Forgery) attack in mvc ? How Preventing (CSRF) Attacks ?
Answer:
CSRF (Cross site request forgery) is a method of attacking a website where the attacker imitates a.k.a forges as a trusted source and sends data to the site. CSRF stands for Cross site request forgery.

To Preventing CSRF attack  we need to add “@Html.AntiForgeryToken” in view with that we need to add this in controller also as a attribute [ValidateAntiForgeryToken] to validating this. Basically AntiForgeryToken is used in HTTPPost method.


3. Ques: What is diffrence between @Html.Action and @Html.RenderAction in mvc ?
Answer :

@Html.Action

This Html.Action renders partial view as an HTML string so we can store it in another string variable. It is string return type method so first it returns result as a string then renders result to response.

@Html.RenderAction

This is also same as Html.Action but main difference is that it renders result directly to response that’s why it is more efficient if the action returns a large amount of HTML over @Html.Action.


4. Ques: How can you remove default View Engine in ASP.NET MVC? ?
Answer:
We can customize view engines in ASP.NET MVC application. If you are not using any view engine like ASPX View Engine, better you remove it to improve the performance.

Removing the Web Form view engine is easy in MVC. We can remove all the view engines and add only Razor view engine by using Application_Start event of Global.asax.cs file like below.

protected void Application_Start()
{
//Remove All Engine
 ViewEngines.Engines.Clear();
 //Add Razor Engine
 ViewEngines.Engines.Add(new RazorViewEngine());
}

5. Ques:  What are Non Action methods in ASP.Net MVC?
Answer:
In ASP.Net MVC all public methods have been treated as Actions. So if you are creating a method and if you do not want to use it as an action method then the method has to be decorated with "NonAction" attribute as shown below :

[NonAction]
public void TestMethod()
{
// Method logic
}


6. Ques:  What is the "HelperPage.IsAjax" Property?
Answer:
The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used during the request of the Web page.


7. Ques:  What is Attribute Routing in ASP.Net MVC?
Answer:
ASP.NET Web API supports this type routing. This is introduced in ASP.Net MVC5. In this type of routing, attributes are being used to define the routes. This type of routing gives more control over classic URI Routing. Attribute Routing can be defined at controller level or at Action level like :

[Route("{action = TestCategoryList}")] - Controller Level
[Route("customers/{TestCategoryId:int:min(10)}")] - Action Level


8. Ques:  What is ViewStart? What are the benifit for ViewStart ? 
Answer:
Razor View Engine introduced a new layout named _ViewStart which is applied on all view automatically. Razor View Engine firstly executes the _ViewStart and then start rendering the other view and merges them.

  • _ViewStart.cshtml page is a special view page containing the statement declaration to include the Layout page.
  • Instead of declaring the Layout page in every view page, we can use the _ViewStart page.
  • When a View Page Start is running, the “_ViewStart.cshtml” page will assign the Layout page for it.

ex:
_viewstart.cshtml
@{
        Layout = "~/Views/Shared/_Layout.cshtml";
 }

Benifit for ViewStart
Instead of declaring the Layout page individually in every page, we can include it on one place only.
So the application became maintainable.
You can still add another page as your Layout page to individual pages, regardless of your _ViewStart page.

9 .What is JSON?
Answer:
JSON full form is JavaScript Object Notation. JSON is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects. And JSON is language-independent, with parsers available for virtually every programming language. Uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python,php  The JSON format is often used for serializing and transmitting structured data over a network connection. When third party data interchane(REST Services) then JSON may used there LIKE SHOP .It is primarily used to transmit data between a server and web application, serving as an alternative to XML.


10. What is JsonResultType in MVC?
Answer:
JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Obect Notation (JSON) format.
Action methods on controllers return JsonResult that can be used in an AJAX application. This class is inherited from the "ActionResult" abstract class. Here Json is provided one argument which must be serializable. The JSON result object that serializes the specified object to JSON format.

public JsonResult JsonResultTest()
{
    return Json("Hello My Friend!");
}   

Wednesday, 1 March 2017

MVC interview questions Part 5

1. Ques: What is Layout in ASP.Net MVC?
Answer:
Layout pages are similar to master pages in traditional web forms.Layout may contains common CSS, jQuery files across the multiple Views and one or more placeholders for which Views provide content. This is used to set the common look across multiple pages.


2. Ques: How we can register the Area in ASP.Net MVC?
Answer:
When we have created an area make sure this will be registered in "Application_Start" event in
Global.asax. Below is the code snippet where area registration is done :

protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();
}

3. Ques: Explain the methods used to render the views in ASP.Net MVC?
Answer:
Below are the methods used to render the views from action -
  • View : To return the view from action.
  • PartialView : To return the partial view from action.
  • RedirectToAction : To Redirect to different action which can be in same controller or in
  • different controller.
  • Redirect : Similar to "Response.Redirect" in webforms, used to redirect to specified URL.
  • RedirectToRoute :Redirect to action from the specified URL but URL in the route table has been matched.

4. Ques:  Explain what is the difference between View and Partial View?
Answer:
View
  • It contains the layout page
  • Before any view is rendered, view start page is rendered
  • View might have markup tags like body, html, head, title, meta etc.
  • View is not lightweight as compare to Partial View
Partial View
  • It does not contain the layout page
  • Partial view does not verify for a viewstart.cshtml. We cannot put common code for a partial view within the viewStart.cshtml.page
  • Partial view is designed specially to render within the view and just because of that it does not consist any mark up
  • We can pass a regular view to the RenderPartial method

5. Ques: In Which two case where routing is not implemented or required?
Answer:
Two case where routing is not required are
  • When a physical file is found that matches the URL pattern
  • When routing is disabled for a URL pattern

6. Ques: What is difference between updatemodel and tryupdatemodel ?
Answer:
UpdateModel(): It will throws an exception, if validation fails.
TryUpdateModel(): It will not never throw an exception.if validation fails.


7. Ques: Explain in short the “page lifecycle” of an ASP.NET MVC?
Answer:
Following process are performed by ASP.Net MVC page:
 App initialization
 Routing
 Instantiate and execute controller
 Locate and invoke controller action
 Instantiate and render view


8. Ques: What is Unobtrusive JavaScript in MVC ?
Answer:
Unobtrusive JavaScript is a general term that conveys a general set of guidelines or margins to the term REST.
REST is nothing but the Representational State Transfer.
We can explain Unobtrusive JavaScript as- it is not your particular JavaScript code that you generally use in your markup page.
Example
In spite of using event attributes like

  • 'onbuttonclick'
  • 'onpageload'
  • 'onsubmit'
  • 'onclick'
  • 'mouseover'

Unobtrusive JavaScript, attaches element directly by their ID or class, in the presence of the other attributes.
MVC 3 uses the concept of Unobtrusive JavaScript in these two:

AJAX helpers
(Such as Ajax. ActionLink and Ajax. BeginFrom)
Ajax helpers are most commonly used with JQuery and extensible attributes.

AJAX validations 
Ajax validations are most commonly used to
JSON Binding, JQuery Validations

Saturday, 25 February 2017

MVC interview questions Part 4

1. Ques: What is Caching ?  What are the advantages of Caching in MVC application and  How implement caching in MVC application ?
Answer:
Caching provides frequently accessed data from memory. It is technique to  improving web application’s performance.
Advantages of Caching 
  • Reduce hosting server round-trips:When content is cached at the client, it can eliminate request to server.
  • Reduce database server round-trips: When content is cached at the web server, it can eliminate the database request.
  • Reduce network traffic: When content is cached at the client side, it it also reduce the network traffic.
  • Avoid time-consumption for reusable content: When reusable content is cached, it avoid the time consumption for reusable content.
  • Improve performance :Since cached content reduce round-trips, network traffic and avoid time consumption for reusable content which cause a improved in the performance.
By using Output Cache Filter we can implement cache  technique in mvc application

OutputCache filter: The OutputCache filter allow you to cache the data that is output of an action method.
By default, this attribute filter cache the data till 60 seconds. After 60 sec, if a call was made to this action then ASP.NET MVC will cache the output again.

You can enable the output caching for an action method or controller by adding an [OutputCache] attribute as shown below:

[OutputCache(Duration=30, VaryByParam="none")]
public ActionResult Index()
{
 ViewBag.Message = DateTime.Now.ToString();
 return View();
}

The output of the Index() action method will be cached for 30 seconds. If you will not defined the duration, it will cached it for by default cache duration 60 sec.


2. Ques: What is Razor View Engine in MVC?
Answer:
  • The Razor View Engine is an advanced view engine, available with MVC 3.0 and later versions.
  • Namespace for ASPX view Engine is Web.Razor.
  • File Extension for this View Engine is .cshtml (Razor C#), for Views, Partial Views, Editor Template and Layout Pages. .vbhtml (Razor VB.NET), for Views, Partial Views, Editor Template and Layout Pages.
  • Supports TDD (Test Driven Development).
  • Razor Engine is little bit slow as compared to Web form Engine.
  • Razor Engine prevents XSS attacks(Cross-Site Scripting Attacks) means it encodes the script or html tags like <,> before rendering to view.
  • Razor syntax is easy to understand and much clean than Web Form syntax. Razor uses @ symbol to make the code.

3. Ques: Explain attribute based routing in MVC?
Answer:
  • Attribute based routing provides more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API. 
  • It is new type of routing introduce in ASP.NET MVC5
attribute based routing Implement in two way one Controller level and another action level

Controller level attribute routing

[RoutePrefix("EmployeeHome")]
[Route("{action=index}")] //default action

public class EmployeeController : Controller
{
 //new route: /EmployeeHome/Index
 public ActionResult Index()
 {
 return View();
 }

 //new route: /EmployeeHome/About
 public ActionResult About()
 {
 ViewBag.Message = "Your application description page.";
 return View();
 }

 //new route: /EmployeeHome/Contact
 public ActionResult Contact()
 {
 ViewBag.Message = "Your contact page."; return View();
 }

}

Action level attribute routing

public class EmployeeController : Controller
{
 [Route("Employee/{id:int:min(100)}")] //route: /Employee/100
 public ActionResult Index(int id)
 {
 return View();
 }

 [Route("Employee/about")] //route" /Employee/about
 public ActionResult About()
 {
 ViewBag.Message = "Employee about page.";
 return View();
 }

 //route: /Home/Contact
 public ActionResult Contact()
 {
 ViewBag.Message = "Employee contact page.";
 return View();
 }
}


4. Ques:  What are Display Modes in MVC4 ?
Answer:
Display modes use a convention-based approach to allow selecting different views based on the browser making the request. The default view engine fi rst looks for views with names ending with .Mobile.cshtml when the browser’s user agent indicates a known mobile device. For example, if we have a generic view titled Index.cshtml and a mobile view titled Index.Mobile.cshtml, MVC 4 will automatically use the mobile view when viewed in a mobile browser.
Additionally, we can register your own custom device modes that will be based on your own custom criteria — all in just one code statement. For example, to register a WinPhone device mode that would serve views ending with .WinPhone.cshtml to Windows Phone devices, you’d use the following code in the Application_Start method of your Global.asax:

Monday, 13 February 2017

MVC interview questions Part 3

1. Ques: What are DataAnnotations in ASP.NET MVC ? List out the DataAnnotation Validator Attributes.
Answer:
Data Annotations used for validate the property of model classes. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace.

DataType: It specify the datatype of a property.
DisplayName: It specify the display name for a property.
DisplayFormat: It specify the display format for a property like different format for Date proerty.
Required: It specify a property as required.
ReqularExpression: it validate the value of a property by specified regular expression pattern.
Range: It validate the value of a property with in a specified range of values.
StringLength:it specify minimum and maximum length for a string property.
MaxLength :it specify max length for a string property.
Bind :it specify fields to include or exclude when adding parameter or form values to model properties.

2. Ques: What is Action Methods in ASP.NET MVC?
Answer:
All the public methods of a Controller class which call from URL are Action methods.Action methods have a one-to-one mapping with user interactions and When a user enters a URL into the browser, the MVC application routing parse the URL and to determine the Action Methods of the controller and execute it.

3. Ques: What are different version of ASP.NET MVC?. And what are the feature inside them?
Answer:
ASP.NET MVC 1
it Runs on Visual Studio 2008(.Net 3.5)
MVC Pattern architecture with WebForm Engine.
Html Helpers.
Ajax helpers.
Routing.
Unit Testing.

ASP.NET MVC 2 
It Runs on Visual Studio 2010(.Net 3.5,& 4.0).
It support Strongly typed HTML helpers.
It support Templated Helpers.
It Support for DataAnnotations Attributes for validation on both client and server sides.
It Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE ?
It Support Areas for partitioning of applications into modules.
It Support Asynchronous controllers.
It Support Binding Binary Data with Model Binders.
It Display Model-Level Errors.
It Support Binding Binary Data with Model Binders.

ASP.NET MVC 3
It Runs on .Net 4.0 and with Visual Studio 2010.
It has Ready made project templates.
It is HTML 5 enabled templates.
It Support for Multiple View Engines.
It Model Validation Improvements.
It is Integrated Scaffolding system.
HTML 5 enabled project templates.
It Support Dependency Injection and Global Action Filters.
It introduce new Razor View Engine.
It Support unobtrusive JavaScript, jQuery Validation, and JSON binding.

ASP.NET MVC 4
It Runs on .Net 4.0 with Visual Studio 2012.
ASP.NET Web API.
Refreshed and modernized default project templates.
New mobile project template.
Many new features to support mobile apps.
Enhanced support for asynchronous methods.
Bundling and minification.
Support for the Windows Azure SDK.
Mobile project template using jQuery Mobile.
Add Controller to other project folder.
It included the entity framework 5 database Migrations.
App_Start folder and separate classes.
Enabling Logins from Facebook and Other Sites Using OAuth and OpenID

ASP.NET MVC 5
It Runs on .Net 4.5 with Visual Studio 2013.
Attribute based routing.
Asp.Net Identity.
Bootstrap in the MVC template.
Authentication Filters.
Filter overrides.
ASP.NET Scaffolding.

ASP.NET MVC 6
Asp.net mvc and Web API has been merged in to one.
Dependency injection is inbuilt and part of MVC.
It Support Side by side - deploy the runtime and framework with your application
Everything packaged with NuGet, Including the .NET runtime itself.
It Support New JSON based project structure.
No need to recompile for every change. Just hit save and refresh the browser.
new Roslyn real-time compiler introduce.
vNext is Open Source via .NET Foundation and is taking public contributions.
vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.

4. Ques: What is Area in ASP.NET MVC? What is advantage of it. 
Answer:
ASP.NET MVC create partition of Web applications into smaller units that is called areas.
Areas was introduced in Asp.net MVC2. Areas provide to separate a large MVC Web application into smaller functional groupings.It separate application into different functional sections like administration, customer support, Employee etc.Areas is very helpful in a large web application.Each MVC area has its own folder which contain controllers, views, and models.

Advantages:
Same mvc application multiple developers can work without interfere to each other.


5. Ques: Which are the important namespaces used in MVC ?
Answer:
  • System.Web.Mvc: It contains classes and interfaces that support the mvc web applications.The classes represent controllers, action results, views, partial views, and model binders etc.
  • System.Web.Mvc.Ajax: It contains classes that supports Ajax scripting in an asp.net mvc application.
  • System.Web.Mvc.Html: It contains classes that help render HTML controls in an mvc application.The classes represent forms, input controls, links, partial views, and validation etc.
  • System.Web.Mvc.Async: It contains classes that support asynchronous actions in an ASP.NET MVC application.

6. Ques: What is Dependency Resolution?
Answer:
MVC 3 introduced a new concept called a dependency resolver, which greatly simplified the use of dependency injection in your applications. This made it easier to decouple application components, making them more configurable and easier to test.
Support was added for the following scenarios:

  •       Controllers (registering and injecting controller factories, injecting controllers)
  •       Views (registering and injecting view engines, injecting dependencies into view pages)
  •       Action fi lters (locating and injecting fi lters)
  •       Model binders (registering and injecting)
  •       Model validation providers (registering and injecting)
  •       Model metadata providers (registering and injecting)
  •       Value providers (registering and injecting)



7. Ques: What is Html.ValidationSummary?
Answer:
ValidationSummary: The ValidationSummary helper method generates an unordered list of validation messages that are in the ModelStateDictionary object. The ValidationSummary can be used to display all the error messages for all the fields. It can also be used to display custom error messages. 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:


8. Ques: What are Scaffold template ?
Answer:
Answer:
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, what code needs to go in each component, and where to place all these pieces in the project for the application to work.


9. Ques: 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 fi eld 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. 

Monday, 6 February 2017

MVC interview questions Part 2

1. Ques: What is Routing in ASP.NET MVC? 
Answer:
Routing is process by which incoming  URL request maps to a specific controller action using a Routing Table. Routing has a RouteTable which define URL pattern that maps to the request handler. All the configured routes of an application stored in RouteTable and will be used by Routing engine to determine appropriate handler class or file for an incoming request.

















2. Ques: What are ASP.NET MVC HtmlHelpers?
Answer:
HtmlHelpers is just a method that returns a HTML string and an HTML string to render HTML tags
HtmlHelpers use to render standard HTML tags like HTML <input>, <button> and <img> tags etc.
It generates html control using the model class object in razor view.

The following are lists of HtmlHelper methods
Html.ActionLink
Html.TextBox
Html.TextArea
Html.CheckBox
Html.RadioButton
Html.DropDownList
Html.ListBox
Html.Hidden
Password
Html.Display
Html.Label
Html.Editor


3. Ques:  What are partial views in MVC ? 
Answer:
Partial view is a view, which can render a inside multiple view.
it can render a view inside a another parental view and to create reusable content in the project.
it is just like a user control in Asp.Net Web forms .Partial store in share folder in application.
partial views used for code re-usability.

there are two method through render the partial view :
Partial -   @Html.Partial("_header")
RenderPartial - Html.RenderPartial("_header")


4. Ques: What is Filters in ASP.NET MVC?  How many Types of filters, explain it.
Answer:
To perform specific logic before or after action methods execution is called Filters.

MVC supports following types of filters:

Authorization Filters: It use for security purpose .It is used to implement authorization and authentication for action filters.this filter  Runs first, before any other filters. Authorize filter attribute implements the IAuthorizationFilter interface. The definition of this interface is given below-
public interface IAuthorizationFilter
{
 void OnAuthorization(AuthorizationContext filterContext);
}

Action Filters:
It used to implement the logic that get executed before or after a controller action executes.The IActionFilter interface is used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which will be executed before or after an action is executed respectively.
public interface IActionFilter
{
 void OnActionExecuting(ActionExecutingContext filterContext);
 void OnActionExecuted(ActionExecutedContext filterContext);
}

Result Filters:
It provide extra logic to gets executed before or after a view result gets executed. Result filters are called after the Action filters. The IResultFilter interface is used to create an Result Filter which provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively.

public interface IResultFilter
{
 void OnResultExecuted(ResultExecutedContext filterContext);
 void OnResultExecuting(ResultExecutingContext filterContext);
}

Exception Filters: Runs only if another action method, or the action result throws an exception. The IExceptionFilter interface is used to create an Exception Filter which provides OnException method which will be executed when exception occurs during the actions execution or filters execution.
public interface IExceptionFilter
{
 void OnException(ExceptionContext filterContext);
}


5. Ques: What is View Engine? What are difference between Razor View Engine and ASPX View Engine?
Answer:
View Engine is responsible for rendering the view into html form to the browser.
There are two type of View Engine Asp.net mvc.
1. Web Form View Engine. (.aspx)
2. Razor View Engine. (.cshtml)

Razor View Engine
  • Razor Engine is an very easy syntax view engine that was introduced with MVC 3.
  • it belong to System.Web.Razor namespace.
  • It has .cshtml (Razor with C#) or .vbhtml (Razor with VB) extension for views.
  • it doesn't support design mode in visual studio.
  • it support TDD (Test Driven Development).
  • Razor View Engine we use Layouts.
  • Razor View Engine we use PartialPage.
  • Razor Engine is a little slow compared to Aspx Engine.
  • Razor Engine prevents Cross-Site Scripting Attacks.
Web Form View Engine

  • It is default view engine for the Asp.net MVC.
  • it belong to System.Web.Mvc.WebFormViewEngine namespace .
  • It has .aspx extension for views.
  • It support design mode in visual studio.
  • It doesn't support TDD (Test Driven Development).
  • ASPX View Engine we use masterPages.
  • ASPX View Engine we use WebUserControls.
  • Aspx Engine is faster compared to Razor Engine.
  • ASPX Engine does not prevent Cross-Site Scripting Attacks.

6. Ques: What are bundling and minification Asp.net MVC ?
Answer:
Bundling:
  • Bundling is technique in which a logical group of files that could be loaded with a single HTTP request.
  • In Bundling multiple file bundle to single file and load at single request.
  • it improves the request load time of the application.
  • Bundle class belong to Microsoft.Web.Optimization namespace.
Ex:
public static void RegisterBundles(BundleCollection bundles) {
     bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
      "~/Content/themes/base/jquery.ui.core.css",
      "~/Content/themes/base/jquery.ui.tabs.css",
      "~/Content/themes/base/jquery.ui.datepicker.css",
      "~/Content/themes/base/jquery.ui.progressbar.css",
      "~/Content/themes/base/jquery.ui.theme.css"));
}

Minification : Minification is process that removing unnecessary characters like white space, newline, tab and comments from the JavaScript and CSS files. Minification reduce the size which cause improved load times of a mvc page.
  • Bundling and Minification are the new features in ASP.NET MVC 4.
  • Bundling and Minification improve the performance of ASP.NET MVC application.


Sunday, 29 January 2017

MVC interview questions Part 1

Ques: Explain MVC architecture?
Answer: 
The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components

Model: Model is a set of classes that describe the business logic for the application data.
View  : View is UI components which  display of the data on browser.
Controller : Controllers responsible to process incoming requests.it manuplate logic with modal and bind data modal with view.


Ques: Explain ASP.NET MVC Pipeline Request Life Cycle?
                         or
          Explain Request Life Cycle of ASP.NET MVC ?
Answer:
Here the diagram show the sequence of Request Life Cycle of ASP.NET MVC.


Request come from IIS enter into url routing module. The routing table find out which
controler action method map to incoming URL pattern. Now in Routing module  there is MVC routeHandler which bring the request to MVC HttpHandler. Now MVC HttpHandler start intilizing of Controler and excute it. The MVCHttpHandler has IControllerFactory factory which responsible for excute instnce of controler. Once the controller has been instantiated, Controller's ActionInvoker determines which specific action to invoke on the controller.once Action method has been finished executing the next step is Result execution.If the result is a view type, the View Engine will be called and it's responsible for finding and rending our view.


Ques:  What are advantages of ASP.NET MVC framework ? 
Answer:
The following lists are the asp.net page life-cycle events.

 Separation of Concerns :It is core advantages MVC framework.The framework divides into three main part Model, View and Controller which make it easier to manage the application complexity.

 Lightweight framework: ASP.NET MVC framework doesn’t View State and thus reduces the bandwidth of the requests to an extent.

Test-driven development : The MVC framework brings better support to test-driven development.Unit Test can done very esaly.

Easy Extensible and pluggable: ASP.NET MVC framework easly customized with diffrent pluggin & Extensible after development over.

Search Engine Optimization (SEO) Friendly : URL's are more friendly for search engines because of URL routing mechanism.

ASP.NET features are supported:  MVC is built on top of ASP.NET so all of the features that ASP.NET include in this framework.

Less change Requirement Time : Developer can do change Requirement very frequently in very less time.

Ques: List out few different return types of a controller action method ?
Answer: 
View Result
Javascript Result
EmptyResult
PartialViewResult
JavaScriptResult
RedirectToRouteResult
Redirect Result
Json Result
Content Result
FileContentResult
FileStreamResult
FilePathResult


Ques: What are the difference between ViewData, ViewBag, Temp data and Session?
Answer: 

ViewData-
  • ViewData is used to pass data from controller to view.
  • It is available for the current request only.
  • ViewData is a dictionary which is derived from ViewDataDictionary class.
  • ViewData requires typecasting for complex data type and check null values to avoid error.
  • If redirection occurs, then its value becomes null.
  • It maintain data when request move from controller to view.
  • ViewData is Faster than ViewBag
  • ViewData is introduced in MVC 1.0
ViewBag-
  • ViewBag is also used to pass data from controller to view.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
  • It is also available for the current request only.
  • If redirection occurs, then its value becomes null.
  • ViewBag doesn’t require typecasting for complex data type.
  • ViewBag is slower than ViewData.
  • ViewBag is introduced in MVC 3.0
TempData-
  • TempData is a dictionary object and it is property of controllerBase class.
  • TempData is used to pass data from one controler to another controler.
  • TempData is only work during the current and subsequent request.
  • TempData is derived from TempDataDictionary class.
  • It requires typecasting for complex data type and checks for null values to avoid error. 
  • It helps to maintain the data when we move from one controller to another controller or from one action to another action
  • TempData introduced in MVC1.0 
Session -
  • Session data mentain for all request until session timeout not expired.
  • Session is valid for all requests, not for a single redirect.
  • It requires typecasting for type and checks for null values to avoid error.
  • Session data are stored in SessionStateItemCollection object.