ASP.NET MVC 6 Interview and Question for Experinced

What is MVC (Model View Controller)?

MVC is Model View Controller. it's architectural pattern which separates the representation and user interaction. It’s divided into three sections, Model, View, and Controller.


Model :- its represents the real world object and provides data to the View.
View :- is responsible for the look and feel all UI Pages.
Controller:- is responsible for taking the end user request and loading the appropriate Model and View.

Explain MVC application life cycle?

Fill route - If the request is the first request the first thing is to fill the route table with routes collection. this filling of route table written in the global.asax file, then MVC requests are mapped to route tables which in turn specify which controller and action to be invoked.
Fetch route - Based on the URL sent “UrlRoutingModule” searche the route table to create
“RouteData” object, which having the details of which controller and action to invoke.
Request context created - The “RouteData” object is used to create the “RequestContext” object.
Controller instance created - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.
What are the benefits of using MVC?

Separation of concerns is achieved as we are moving the code-behind to a separate class file. By moving the binding code to a separate class file we can reuse the code to a great extent.
Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple .NET class. This gives us opportunity to write unit tests and automate manual testing.

What is the latest version of MVC? 

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

What is the difference between each version of MVC 3 , 4, 5 ?

MVC 5

One ASP.NET Framework with all libararies
Attribute based routing
Asp.Net Identity
Bootstrap in the MVC template
Authentication Filters
Filter overrides

MVC 4

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

MVC 3

Razor
Readymade project templates
HTML 5 enabled templates
Support for Multiple View Engines
JavaScript and Ajax
Model Validation Improvements

What are Filters in MVC?

Generally filter used to perform some action before or after a particular operation. MVC provides feature to add pre and post action behaviors on controller's action methods invoke.

Types of Filters:
  1. Action Filters: used to implement logic that gets executed before and after a controller action executes.
  2. Authorization Filters: used to implement authentication and authorization for controller actions.
  3. Result Filters: contains logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
  4. Exception Filters: use an exception filter to handle errors raised by either your controller actions or controller action results. You can also use exception filters to log errors.
Explain routing in MVC? What are the three segments for routing important?

Routing is a to process the incoming URL and give desired response.

Two types of routing
Convention based routing: we call MapRoute method and set its unique name, url pattern and specify some default values.
Attribute based routing: we specify the Route attribute in the above action method of the controller.

Three segments for routing

ControllerName
ActionMethodName
Parammeter

Example : ControllerName/ActionMethodName/{ParamerName} and Attribute Name which is define above the action method name.

Explain attribute based routing in MVC?

ASP.NET MVC 5.0 we have a new attribute route,cBy using the "Route" attribute we can define the URL structure.

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

Where is the route mapping code written?

The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.
Can we map multiple URL’s to the same action?
Yes, you can, you just need to make two entries with different key names and specify the same controller and action.

what is the difference between Temp data, View, and View Bag?

There are mainly three ways to store & pass data between the controllers and views.

ViewData
ViewData is used to pass data from controller to view.
It is derived from ViewDataDictionary class.
It is available for the current request only.
Requires typecasting for complex data type and checks for null values to avoid error.
If redirection occurs, then its value becomes null.

ViewBag
ViewBag is also used to pass data from the controller to the respective 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.
Doesn’t require typecasting for complex data type.

TempData
TempData is derived from TempDataDictionary class
TempData is used to pass data from the current request to the next request
It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages

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.

What is the use of Keep and Peek in “TempData”?
If we want “TempData” to be read and also available in the subsequent request then after reading we need to call “Keep”.

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

What is Partial View in MVC?

Partial view is a reusable view (like a user control) which can be embedded inside other view.

A partial view is a chunk of HTML that can be safely inserted into an existing DOM. Most commonly, partial views are used to componentize Razor views and make them easier to build and update. Partial views can also be returned directly from controller methods.

let’s say all the pages of your site have a standard structure with left menu, header, and footer as partial view and fit to in main layout page.

what is the difference between View and Partial View?

View:
It contains the layout page.
Before any view is rendered, viewstart 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.

What is Razor in MVC?

It’s a light weight view engine. MVC 3 has introduced a new view engine called Razor.
As per Microsoft,, Razor is clean, lightweight, and syntaxes are easy as compared to ASPX.

Features of Razor
Easy to Learn
Compact & Expressive
Razor minimizes the number of lines in codes
Works with any Text Editor
Has great Intellisense
Unit Testable
Prevents Cross Site Scripting (XSS) attacks by encoding the script or HTML tags before rendering to the view.
MVC also supports third-party packages

How can you do authentication and authorization in MVC?
You can use Windows or Forms authentication for MVC.

Windows authentication you need to modify the web.config file

<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>

you can use the Authorize attribute which specifies which users have access to these controllers and actions.

[Authorize(Users= @"Home\Administrator")]
public class HomeController : Controller {
   // // GET: /Start/
   [Authorize(Users = @"Home\Administrator")]
   public ActionResult Index() {
       return View("MyView");
   }
}

Forms authentication is implemented the same way as in ASP.NET.

<authentication mode="Forms">
     <forms loginUrl="~/Home/Login" timeout="2880"/>
</authentication>

If the user is proper we will set the cookie value.
public ActionResult Login() {


    if((Request.Form["txtUser"]=="Darshak") && Request.Form["txtPassword"]          == "darshak@987"))
       FormsAuthentication.SetAuthCookie("Shiv",true);
       return View("About");
  }
  else {
       return View("Index");
   }
}

Authorize attribute so that we can verify its authorize request or not?
[Authorize] 
Public ActionResult Default() {
 return View();
}

What are HTML helpers in MVC?
HTML helpers are used to modify HTML. But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state.
you can create your own helpers, or use the built in HTML helpers.
Syntax:

<%=Html.ActionLink("Welcome to Our Website", "Home")%>

The first parameter is the link text, and the second parameter is the name of the controller action.
HTML Form Elements:

BeginForm()
EndForm()
TextArea()
TextBox()
CheckBox()
RadioButton()
ListBox()
DropDownList()
Hidden()
Password()

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

How can we do validations in MVC OR what is Data annotations?

Data annotations easiest ways of doing validation in MVC. Data annotations are nothing but attributes which can be applied on model properties.

For Example:-
public class Employee { [Required(ErrorMessage="Employeecode is required")]
public string EmployeeCode
{ get;set; } }

For display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

<%=Html.ValidationMessageFor(m => m.EmployeeCode)%>

we can check if the model is proper or not by using the ModelState.IsValid property.
using the ValidationSummary display all errors messages.

<%= Html.ValidationSummary() %>

Different type of data annotation attributes.

StringLength
[StringLength(75)] public string Email { get; set; }

RegularExpression
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; }

Range
[Range(18,125)]public int Age { get; set; }

Compare
public string Password { get; set; }
[Compare("Password")]
public string ConfirmPass { get; set; }

Errors
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;

TryUpdateModel - to check if the object is valid or not.

TryUpdateModel(NewCustomer);

AddModelError

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

How can we enable data annotation validation on client side?

using below statment we can achieve client side validation.

<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript">
</script> 

<script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript">

<% Html.EnableClientValidation(); %>

What are the different types of results in MVC?

In MVC, ActionResult class which is a base class which have 11 sub classes as listed below:
ViewResult - Renders a specified view to the response stream
PartialViewResult - Renders a specified partial view to the response stream
EmptyResult - An empty response is returned
RedirectResult - Performs an HTTP redirection to a specified URL
RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
JsonResult - Serializes a given ViewData object to JSON format
JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
ContentResult - Writes content to the response stream without requiring a view
FileContentResult - Returns a file to the client
FileStreamResult - Returns a file to the client, which is provided by a Stream
FilePathResult - Returns a file to the client

What is Bundling and Minification in MVC?

Bundling: It combine multiple JavaScript (.js) files or multiple cascading style sheet (.css) files into one file so that they can be downloaded as a one file, rather than making individual HTTP requests for all files.

Minification: It squeezes out whitespace and performs other types of compression to make the downloaded files as small as possible. created minified version of actual file which is very light weight.

Explain Areas in MVC?
ASP.Net MVC 2.0 Microsoft provided a new feature in MVC applications, Areas. Areas are just a way to divide or “isolate” the modules of large applications in multiple or separated MVC.

Benefits of Area in MVC
Allows us to organize models, views and controllers into separate functional sections of the application, such as administration, billing, customer support and much more.
Easy to integrate with other Areas created by another.
Easy for unit testing.

What are the methods of handling an Error in MVC?

Exception handling may be required in any application, whether it is a web application or a Windows Forms application.

Attribute called "HandleError" that provides built-in exception filters.

HandleError attribute is added within the Global.asax.cs file and registered in the Application_Start event.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
      filters.Add(new HandleErrorAttribute());
}
protected void Application_Start()
{
}

We can set Error Handle at controller level and action level also we can set using attribute.

[HandleError(View = "Error")]
public class HomeController: Controller
{
[HandleError(View = "Error")]
public ActionResult Index()
{
}
}

How can we use two ( multiple) models with a single view?
view we can refer both the model using the view model as per below

public class CustOrderVM {
     public Customer cust = new Customer();
     public Order Ord = new Order();
}

<%= model.cust.Name %> <%= model.Ord.Number %>

Explain the need of display mode in MVC?

Display mode displays views depending on the device the user has logged in with. So we can create different views for different devices and display mode will handle the rest.

What is WebAPI?

HTTP is the most used protocol. For the past many years, browser was the most preferred client by which we consumed data exposed over HTTP. But as years passed by, client variety started spreading out. We had demand to consume data on HTTP from clients like mobile, JavaScript, Windows applications, etc.
For satisfying the broad range of clients REST was the proposed approach. You can read more about REST from the WCF chapter.
WebAPI is the technology by which you can expose data over HTTP following REST principles.

Different between WCF SOAP & WEB API?
SOAP
  • Heavy weight because of complicated WSDL structure.
  • Independent of protocols.
  • To parse SOAP message, the client needs to understand WSDL format. Writing custom code for parsing WSDL is a heavy duty task. If your client is smart enough to create proxy objects like how we have in .NET (add reference) then SOAP is easier to consume and call.
  • SOAP follows WS-* specification.
WEB API
  • Light weight, only the necessary information is transferred.
  • Only for HTTP protocol
  • Output of WebAPI are simple string messages, JSON, simple XML format, etc. So writing parsing logic for that is very easy.
  • WebAPI follows REST principles.


Comments

Popular posts from this blog

Angular 4 interview questions and answers for experience

8). Vue.js Methods and Event Handling

12). Vue JS - Slots