Asp.net MVC Interview Question part-3

Asp.net MVC Interview Question part-3

 

 

1.)Difference b/w let and var?

let gives you the privilege to declare variables that are limited in scope to the block, statement of expression unlike var.

var is rather a keyword which defines a variable globally regardless of block scope.

2.)What is bubbling

The bubbles event property returns a Boolean value that indicates whether or not an event is a bubbling event.Event bubbling directs an event to its intended target, it works like this:

A button is clicked and the event is directed to the button If an event handler is set for that object, the event is triggered

If no event handler is set for that object, the event bubbles up (like a bubble in water) to the objects parent. The event bubbles up from parent to parent until it is handled, or until it reaches the document object.

3.)What is propogation

Event Capture and Bubbling

The DOM has two ways for objects to detect events: from the top down, and from the bottom up. The first method is known as event capture, the second is called event bubbling

Event Capture

Let's say that your document contains a <div> which contains a <p> which contains an <img>. Further, let's say you've added an event listener to all of them. When a user clicks on the image, a mouseclick event occurs.Even though the user clicked the image, the image doesn't get the event first. 

Instead, the event listener attached to the document grabs the event first and processes it. (That is, it captures the event before it gets to its intended target.) The event is then passed down to the <div>'s event listener. The event then goes to the <p>, and finally to the <img>. That is, all of the clicked-on object's “ancestors” higher up in the document capture the event for processing before sending it down the chain to its intended target. You can try event capture in a pop-up window. (This only works in Mozilla.)

Event Bubbling

Now let's look at the same situation from the inside out. You have an <img> inside a <p>, which is inside a <div>, which is inside your document.

When a user clicks the image, this time the events rise like a bubble in a glass of water. The click's original target, the <img>, gets to see the event first, and then passes it upwards to the <p> for further processing, which passes it on to the <div>, which finally passes it up to the document. You can try event bubbling in a pop-up window. (This only works in Mozilla.) 

Event propagation is a way to describe the “stack” of events that are fired in a web browser. In our table example above, clicking on the a tag is the first event that we will fire, but there are other events too.

To understand that concept, you must understand that the elements on a web browser are nested. They do not cover each other up. So a click on the a tag also clicks on the row, the table, the div in which the table is nested, and anything else all the way out to document , the complete container that holds everything in your browser.

If we’ve put any other onClick events inside of these other elements, they will also be fired when we click on the a link in the table. That’s why we will be directed to the user record when we click on the email link. It’s going to perform both the onClick function for the a link and the onClick function for the row.

Bubbles

The movement of events “up” from the most-nested element ( a) out to the least-nested ( document) is referred to as “bubbling.” If events start in the “outer-most” element and moved “down,” that is referred to as “trickling.” All you probably care about is the default behavior: bubbling.

How to use event propagation to your advantage

Honestly, I hadn’t run into any use-case for caring about event propagation until this week, when I needed to build a table with a checkbox in it. Unfortunately for me, when I tried to set up the checking functionality, it took me to the record. Fortunately, I did some training earlier (see references below) that gave me a clue on exactly what I had to Google.

 
You probably already know that when you create an onClick event, it is passed to whatever function you call.
So here, I was able to write:
handleCheck = e => {
  e.stopPropagation()
  // talk to my API, set the record as "done" or not
}

 

4.) Session in mvc

TempData:
  • is the property of the ControllerBase class
  • is used to pass data from one controller to other
  • its life is ended when the target view is loaded completely
  • it is recommended to type-cast the value when TempData value is used for processing
  • Mostly used to store Validation Error Messages, etc.
  • The Life time of the TempData can be managed using the Keep() method.

ViewData

  • It is Key-Value Dictionary collection
  • ViewData is a dictionary object and it is property of ControllerBase class
  • ViewData is Faster than ViewBag
  • Type Conversion code is required while enumerating
  • Its value becomes null if redirection has occurred.
  • It lies only during the current request.
ViewBag
  • It is a type object
  • ViewBag is Dynamic property of ControllerBase class.
  • ViewBag is slower than ViewData
  • In depth, ViewBag is used dynamic, so there is no need to type conversion while enumerating.
  • Its value becomes null if redirection has occurred.
  • It lies only during the current request.

5.)Routing and types

 

Routing is a mechanism to process the incoming url that is more descriptive and give desired response. In this case, URL is not mapped to specific files or folder as was the case of earlier days web sites.

There are two types of routing (after the introduction of ASP.NET MVC 5).

Convention based routing - to define this type of routing, we call MapRoute method and set its unique name, url pattern and specify some default values.

Attribute based routing - to define this type of routing, we specify the Route attribute in the action method of the controller.

syntax of routing
routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
     );

6.)View state

 

View State is the method to preserve the Value of the Page and Controls between round trips. It is a Page-Level State Management technique. 

View State is turned on by default and normally serializes the data in every control on the page regardless of whether it is actually used during a post-back.

Features Of View State

  • Retains the value of the Control after post-back without using a session.
  • Stores the value of Pages and Control Properties defined in the page.
  • Creates a custom View State Provider that lets you store View State Information in a SQL Server Database or in another data store.

7.)Difference b/w view state and session

 

Session State contains information that is pertaining to a specific session (by a particular client/browser/machine) with the server. It's a way to track what the user is doing on the site.. across multiple pages...amid the statelessness of the Web. e.g. the contents of a particular user's shopping cart is session data. Cookies can be used for session state.

View State on the other hand is information specific to particular web page. It is stored in a hidden field so that it isn't visible to the user. It is used to maintain the user's illusion that the page remembers what he did on it the last time - dont give him a clean page every time he posts back.

8.)window.load and document.ready

Both functions are used to perform tasks when the page is loaded in the browser but they have important differences. 

Most importantly, “window.onload” will execute code when browser has loaded the DOM tree and all other resources like images, objects, etc, 

while onDocumentReady allows you to execute code when only the DOM tree has been built, without waiting for images to load. 

Thus, you can start scripting agains the DOM much quicker with onDocumentReady. 

Another important difference is that window.onload is not cross-browser compatible while using something like jQuery’s document.ready() will work nicely on all browsers.

9.)Difference b/w abstract class and interface

Interface
  • A class may inherit several interfaces.
  • An interface cannot provide any code, just the signature.
  • An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public.
  • Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
  • If various implementations only share method signatures then it is better to use Interfaces.
  • Requires more time to find the actual method in the corresponding classes.
  • If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
  • No fields can be defined in interfaces
Abstract class
  • A class may inherit only one abstract class.
  • An abstract class can provide complete, default code and/or just the details that have to be overridden.
  • An abstract class can contain access modifiers for the subs, functions, properties.
  • An abstract class defines the core identity of a class and there it is used for objects of the same type.
  • If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
  • It is faster as compare to interface.
  • If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
  • An abstract class can have fields and constrants defined.

10.)Difference b/w view and partialview

partial view() is Reusable view.but view() is a single page means which will render a normal page.

A partial view is a "sub-view" that you embed within a main view - something that you might reuse across multiple views, like a sidebar. In theory, partial views are more lightweight than standard views, 

but it's perfectly OK to pass a "regular" view to RenderPartial and the performance seems to be exactly the same. I frequently use regular .aspx views as "partial" views because you can make them reference a master view in order to provide templated content 

like what you can do with UserControls in ASP.NET WebForms.

Partial views are more like web parts on a portal - they are completely self-contained objects. Use them if the layout is simple and static, or if you're annoyed by the Intellisense errors when you don't have the <html> and <body> tags in a standard View.

11.)Namespace for data annotations

System.ComponentModel.DataAnnotations

12.)Types of data annotations and syntax

Required-This attribute specifies that the value is mandatory and cannot be skipped.
Syntax
[Required(ErrorMessage="Please enter name"),MaxLength(30)]
DataType-This attribute is used to specify the datatype of the model.
Syntax
[DataType(DataType.Text)]
Range-Using this attribute we can set a range between two numbers.
Syntax
[Range(100,500,ErrorMessage="Please enter correct value")]
StringLength-Using this attribute we can specify maximum and minimum length of the property.
Syntax
[StringLength(30,ErrorMessage="Do not enter more than 30 characters")]
DisplayName-Using this attribute we can specify property name to be displayed on view.
Syntax
[Display(Name="Student Name")]
MaxLength-Using this attribute we can specify maximum length of property.
Syntax
[MaxLength(3)]
Bind-This attribute specify fields to include or exclude for model binding.
Syntax
[Bind(Exclude = "StudentID")]
DisplayFormat-This attribute allows us to set date in the format specified as per the attribute.
Syntax
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]

RegularExpression-We can set a regex pattern for the property. For ex: Email ID.

Syntax
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid.")]

13.)Filters and Ordering

Authorization filters Performs authentication and authorizes before executing action method. [Authorize], [RequireHttps] IAuthorizationFilter

Action filters Performs some operation before and after an action method executes. IActionFilter

Result filters Performs some operation before or after the execution of view result. [OutputCache] IResultFilter

Exception filters Performs some operation if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. [HandleError] IExceptionFilter

14.)Dependency Injection in C#

Dependency Injection (DI) is a software design pattern. It allows us to develop loosely-coupled code. The intent of Dependency Injection is to make code maintainable. Dependency Injection helps to reduce the tight coupling among software components. 

Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically. This article explains how to implement Dependency Injection in C# and .NET code.

We have the following ways to implement Dependency Injection.
 
Constructor Injection

This is the most commonly used dependency pattern in Object Oriented Programming.The constructor injection normally has only one parameterized constructor, so in this constructor dependency there is no default constructor and we need to pass the specified value at the time of object creation. We can use the injection component anywhere within the class.  It addresses the most common scenario where a class requires one or more dependencies.

Property Injection
 

We use constructor injection, but there are some cases where I need a parameter-less constructor so we need to use property injection.

Method Injection
 

In method injection we need to pass the dependency in the method only. The entire class does not need the dependency, just the one method. I have a class with a method that has a dependency. I do not want to use constructor injection because then I would be creating the dependent object every time this class is instantiated and most of the methods do not need this dependent object.

 

Find more questions below

  1. Aspnet-Interview-Questions-part-1
  2. Asp-net-Interview-Quetions-part-2

 

 

Add comment

CommentList

The file '/Custom/Widgets/ScriptInjection/widget.cshtml' does not exist.