return View()

advertisement
1. Explain MVC (Model-View-Controller) in general?
MVC (Model-View-Controller) is an architectural software pattern that basically decouples
various components of a web application. By using MVC pattern, we can develop applications
that are more flexible to changes without affecting the other components of our application.
"Model" is basically domain data.
"View" is user interface to render domain data.
"Controller" translates user actions into appropriate operations performed on model.
2. What is ASP.NET MVC?
ASP.NET MVC is a web development framework from Microsoft that is based on MVC (ModelView-Controller) architectural design pattern. Microsoft has streamlined the development of
MVC based applications using ASP.NET MVC framework.
3. Difference between ASP.NET MVC and ASP.NET WebForms?
ASP.NET Web Forms uses Page controller pattern approach for rendering layout, whereas
ASP.NET MVC uses Front controller approach. In case of Page controller approach, every page
has its own controller, i.e., code-behind file that processes the request. On the other hand, in
ASP.NET MVC, a common controller for all pages processes the requests.
Follow the link for the difference between the ASP.NET MVC and ASP.NET WebForms.
4. What are the Core features of ASP.NET MVC?
Core features of ASP.NET MVC framework are:
Clear separation of application concerns (Presentation and Business Logic)
An extensible and pluggable framework
Extensive support for ASP.NET Routing
Support for existing ASP.NET features
Follow for detailed understanding of the above mentioned core features.
5. Can you please explain the request flow in ASP.NET MVC framework?
Request flow for ASP.NET MVC framework is as follows:
Request hits the controller coming from client. Controller plays its role and decides which
model to use in order to serve the request further passing that model to view which then
transforms the model and generates an appropriate response that is rendered to the client.
6. 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. ASP.NET MVC framework uses friendly URLs that more easily describe user’s action
but are not mapped to physical files.
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 appropriate
controller.
Practically, when a user types a URL in a browser window for an ASP.NET MVC application and
presses “go” button, routing engine uses routing rules that are defined in Global.asax file in
order to parse the URL and find out the path of corresponding controller.
7. What is the difference between ViewData, ViewBag and TempData?
In order to pass data from controller to view and in 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 controller and corresponding
view. But this communication is only for server call, it becomes null if redirect occurs. So, in
short, it's a mechanism to maintain state between 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, Tempdata
can be used to maintain data between redirects, i.e., from one controller to the other
controller.
8. What are Action Methods in ASP.NET MVC?
I already explained about request flow in ASP.NET MVC framework that request coming from
client hits controller first. Actually MVC application determines the corresponding controller by
using routing rules defined in Global.asax. And controllers have specific methods for each user
actions. Each request coming to controller is for a specific Action Method. The following code
example, “ShowBooks” is an example of an Action method.
Collapse | Copy Code
public ViewResult ShowBooks(int id)
{
var computerBook = db.Books.Where(p => P.BookID == id).First();
return View(computerBook);
}
9. Explain the role of Model in ASP.NET MVC?
One of the core features of ASP.NET MVC is that it separates the input and UI logic from
business logic. Role of Model in ASP.NET MVC is to contain all application logic including
validation, business and data access logic except view, i.e., input and controller, i.e., UI logic.
Model is normally responsible for accessing data from some persistent medium like database
and manipulate it.
10. 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 means 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.
ASP.NET WebForms
Uses the ‘Page Controller’ pattern. Each
page has a code-behind class that acts as
a controller and is responsible for
rendering the layout.
ASP.NET MVC
Uses the ‘Front Controller’ pattern.
There is a single central controller for all
pages to process web application
requests and facilitates a rich routing
architecture
Uses an architecture that combines the
Controller (code behind) and the View
(.aspx). Thus the Controller has a
ASP.NET MVC enforces a "separation
of concerns". The Model does not know
anything about the View. The View
dependency on the View. Due to this,
testing and maintainability becomes an
issue.
does not know there’s a Controller. This
makes MVC applications easier to test
and maintain
The View is called before the Controller. Controller renders View based on
actions as a result of the User
Interactions on the UI.
At its core, you ‘cannot’ test your
controller without instantiating a View.
There are ways to get around it using
tools.
At its core, ASP.NET MVC was
designed to make test-driven
development easier. You ‘can’ test your
Controller without instantiating a View
and carry out unit-tests without having
to run the controllers in an ASP.NET
process.
WebForms manage state by using view
state and server-based controls.
ASP.NET MVC does not maintain state
information by using view state
WebForms supports an event-driven
programming style that is like Windows
applications and is abstracted from the
user. The State management is made
transparent by using sessions, viewstate
etc. In the process, the HTML output is
not clean making it difficult to manage
later. The ViewState also increases your
page size.
In ASP.NET MVC, the output is clean
and you have full control over the
rendered HTML. The orientation is
towards building standard compliant
pages and provides full control over the
behavior of an application.
Deep understanding of HTML, CSS and
JavaScript is not required to a large
extent since the WebForm model
abstracts a lot of these details and
provides automatic plumbing. While
abstracting details to provide ease of use,
sometimes a solution is overcomplicated,
than it needs to be.
A thorough understanding of how
HTML, CSS and JavaScript work
together is required. The advantage is
you can do a lot of jQuery and AJAX
stuff in an efficient and simple manner
than you would do in an ASP.NET
application.
WebForms can drastically reduce time
while building up intranet and internet
applications that use a lot of controls
(drag and drop model). Although this is
true for development, a lot of time is
spent later to code around limitations.
You lose the 'drag and drop' quick
model of building your web
applications. The focus is on control
over the application behavior and testdriven development. The model is
extensible and you do not have to spend
time working around limitations.
Relatively simple to learn and pickup.
There is a learning curve to understand
Works very well for developers who
the why, when and how of ASP.NET
initially have trouble with the
MVC.
HTTP/HTML model and are coming
from a similar WinForms oriented event
model.
Lesser amount of code is required to
build webapps since a lot of components
are integrated and provided out of the
box. You can also use a lot of data
controls provided out of the box that rely
on ViewState.
Since the application tasks are separated
into different components, amount of
code required is more. Since ASP.NET
MVC does not use ViewState, you
cannot use Data controls like GridView,
Repeater.
Works very well for small teams where
focus is on rapid application
development
Works well for large projects where
focus in on testability and
maintainability
What is MVC (Model View Controller)?
MVC is an architectural pattern which separates the representation and user interaction. It’s
divided into three broader sections, Model, View, and Controller. Below is how each one of
them handles the task.



The View is responsible for the look and feel.
Model represents the real world object and provides data to the View.
The Controller is responsible for taking the end user request and loading the appropriate
Model and View.
Figure: MVC (Model view controller)
Explain MVC application life cycle?
There are six broader events which occur in MVC application life cycle below diagrams
summarize it.
Image Courtesy: - http://www.dotnetinterviewquestions.in/article_explain-mvc-application-lifecycle_210.html
Any web application has two main execution steps first understanding the request and depending
on the type of the request sending out appropriate response. MVC application life cycle is not
different it has two main phases first creating the request object and second sending our response
to the browser.
Creating the request object: -The request object creation has four major steps. Below is the
detail explanation of the same.
Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which
controller and action to be invoked. So if the request is the first request the first thing is to fill the
route table with routes collection. This filling of route table happens in the global.asax file.
Step 2 Fetch route: - Depending on the URL sent “UrlRoutingModule” searches the route table
to create “RouteData” object which has the details of which controller and action to invoke.
Step 3 Request context created: - The “RouteData” object is used to create the
“RequestContext” object.
Step 4 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.
Creating Response object: - This phase has two steps executing the action and finally sending
the response as a result to the view.
Is MVC suitable for both Windows and Web applications?
The MVC architecture is suited for a web application than Windows. For Window applications,
MVP, i.e., “Model View Presenter” is more applicable. If you are using WPF and Silverlight,
MVVM is more suitable due to bindings.
What are the benefits of using MVC?
There are two big benefits of 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.
Is MVC different from a three layered architecture?
MVC is an evolution of a three layered traditional architecture. Many components of the three
layered architecture are part of MVC. So below is how the mapping goes:
Functionality
Look and Feel
UI logic
Business logic
/validations
Request is first sent to
Accessing data
Three layered / tiered
architecture
User interface
User interface
Model view controller architecture
View
Controller
Middle layer
Model
User interface
Data access layer
Controller
Data Access Layer
Figure: Three layered architecture
What is the latest version of MVC?
MVC 6 is the latest version which is also termed as ASP VNEXT.
What is the difference between each version of MVC 2, 3 , 4, 5 and 6?
MVC 6
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.
MVC 5
One ASP.NET
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
MVC 2
Client-Side Validation
Templated Helpers
Areas
Asynchronous Controllers
Html.ValidationSummary Helper Method
DefaultValueAttribute in Action-Method Parameters
Binding Binary Data with Model Binders
DataAnnotations Attributes
Model-Validator Providers
New RequireHttpsAttribute Action Filter
Templated Helpers
Display Model-Level Errors
What are HTML helpers in MVC?
HTML helpers help you to render HTML controls in the view. For instance if you want to
display a HTML textbox on the view , below is the HTML helper code.
Collapse | Copy Code
<%= Html.TextBox("LastName") %>
For checkbox below is the HTML helper code. In this way we have HTML helper methods for
every HTML control that exists.
Collapse | Copy Code
<%= Html.CheckBox("Married") %>
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 which just creates a simple textbox with
“CustomerCode” as name.
Collapse | Copy Code
Html.TextBox("CustomerCode")
Below is “Html.TextBoxFor” code which creates HTML textbox using the property name
‘CustomerCode” from object “m”.
Collapse | Copy Code
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”.
What is routing in MVC?
Routing helps you to define a URL structure and map the URL with the controller.
For instance let’s say we want that when a user types “http://localhost/View/ViewCustomer/”, it
goes to the “Customer” Controller and invokes the DisplayCustomer action. This is defined
by adding an entry in to the routes collection using the maproute function. Below is the
underlined code which shows how the URL structure and mapping with controller and action is
defined.
Collapse | Copy Code
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action =
"DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults
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.
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".
Collapse | Copy Code
public class HomeController : Controller
{
[Route("Users/about")]
public ActionResult GotoAbout()
{
return View();
}
}
What is the advantage of defining route structures in the code?
Most of the time developers code in the action methods. Developers can see the URL structure
right upfront rather than going to the “routeconfig.cs” and see the lengthy codes. For instance in
the below code the developer can see right upfront that the “GotoAbout” action can be invoked
by four different URL structure.
This is much user friendly as compared to scrolling through the “routeconfig.cs” file and going
through the length line of code to figure out which URL structure is mapped to which action.
Collapse | Copy Code
public class HomeController : Controller
{
[Route("Users/about")]
[Route("Users/WhoareWe")]
[Route("Users/OurTeam")]
[Route("Users/aboutCompany")]
public ActionResult GotoAbout()
{
return View();
}
}
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 which helps to navigate to the “Home” controller and invoke the GotoHome action.
Collapse | Copy Code
<%= Html.ActionLink("Home","Gotohome") %>
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 you 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.
Collapse | Copy Code
[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}
How can we maintain sessions in MVC?
Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.
What is the difference between tempdata, viewdata, and viewbag?
Figure: Difference between tempdata, viewdata, and viewbag



Temp data - Helps to maintain data when you move from one controller to another
controller or from one action to another action. In other words when you redirect,
tempdata helps to maintain data between those redirects. It internally uses session
variables.
View data - Helps to maintain data when you move from controller to view.
View Bag - It’s a dynamic wrapper around view data. When you use Viewbag type,
casting is not required. It uses the dynamic keyword internally.
Figure: dynamic keyword


Session variables - By using session variables we can maintain data from any entity to
any entity.
Hidden fields and HTML controls - Helps to maintain data from UI to controller only.
So you can send data from HTML controls or hidden fields to the controller using POST
or GET HTTP methods.
Below is a summary table which shows the different mechanisms for persistence.
Maintains data
between
Controller to
Controller
Controller to View
View to Controller
ViewData/ViewBag TempData
Hidden fields Session
No
Yes
No
Yes
Yes
No
No
No
No
Yes
Yes
Yes
What is difference between TempData and ViewData ?
“TempData” maintains data for the complete request while “ViewData” maintains data only
from Controller to the view.
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”?
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.
Collapse | Copy Code
@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.
Collapse | Copy Code
string str = TempData.Peek("Td").ToString();
If you want to read more in detail you can read from this detailed blog on MVC Peek and Keep.
What are partial views in MVC?
Partial view is a reusable view (like a user control) which can be embedded inside other view.
For example let’s say all your pages of your site have a standard structure with left menu, header,
and footer as shown in the image below.
Figure: Partial views in MVC
For every page you would like to reuse the left menu, header, and footer controls. So you can go
and create partial views for each of these items and then you call that partial view in the main
view.
How did you create a partial view and consume it?
When you add a view to your project you need to check the “Create partial view” check box.
Figure: Create partial view
Once the partial view is created you can then call the partial view in the main view using the
Html.RenderPartial method as shown in the below code snippet:
Collapse | Copy Code
<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>
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 which can be applied on model properties. For example, in
the below code snippet we have a simple Customer class with a property customercode.
This CustomerCode 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.
Collapse | Copy Code
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.
Collapse | Copy Code
<% using (Html.BeginForm("PostCustomer", "Home",
FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%>
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 actions.
Collapse | Copy Code
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Customer");
}
}
Below is a simple view of how the error message is displayed on the view.
Figure: Validations in MVC
Can we display all errors in one go?
Yes, we can; use the ValidationSummary method from the Html helper class.
Collapse | Copy Code
<%= Html.ValidationSummary() %>
What are the other data annotation attributes for validation in MVC?
If you want to check string length, you can use StringLength.
Collapse | Copy Code
[StringLength(160)]
public string FirstName { get; set; }
In case you want to use a regular expression, you can use the RegularExpression attribute.
Collapse | Copy Code
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Zaz]{2,4}")]public string Email { get; set; }
If you want to check whether the numbers are in range, you can use the Range attribute.
Collapse | Copy Code
[Range(10,25)]public int Age { get; set; }
Sometimes you would like to compare the value of one field with another field, we can use the
Compare attribute.
Collapse | Copy Code
public string Password { get; set; }[Compare("Password")]public
string ConfirmPass { get; set; }
In case you want to get a particular error message , you can use the Errors collection.
Collapse | Copy Code
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;
If you have created the model object yourself you can explicitly call TryUpdateModel in
your controller to check if the object is valid or not.
Collapse | Copy Code
TryUpdateModel(NewCustomer);
In case you want add errors in the controller you can use the AddModelError function.
Collapse | Copy Code
ModelState.AddModelError("FirstName", "This is my server-side
error.");
How can we enable data annotation validation on client side?
It’s a two-step process: first reference the necessary jQuery files.
Collapse | Copy Code
<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>"
type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>"
type="text/javascript"></script>
<script src="<%=
Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>"
type="text/javascript"></script>
The second step is to call the EnableClientValidation method.
Collapse | Copy Code
<% Html.EnableClientValidation(); %>
What is Razor in MVC?
It’s a light weight view engine. Till MVC we had only one view type, i.e., ASPX. Razor was
introduced in MVC 3.
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:
Collapse | Copy Code
<%=DateTime.Now%>
In Razor, it’s just one line of code:
Collapse | Copy Code
@DateTime.Now
So which is a better fit, Razor or ASPX?
As per Microsoft, Razor is more preferred because it’s light weight and has simple syntaxes.
How can you do authentication and authorization in MVC?
You can use Windows or Forms authentication for MVC.
How to implement Windows authentication for MVC?
For Windows authentication you need to modify the web.config file and set the authentication
mode to Windows.
Collapse | Copy Code
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
Then in the controller or on the action, you can use the Authorize attribute which specifies
which users have access to these controllers and actions. Below is the code snippet for that. Now
only the users specified in the controller and action can access it.
Collapse | Copy Code
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
public ActionResult Index()
{
return View("MyView");
}
}
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.
Collapse | Copy Code
<authentication mode="Forms">
<forms loginUrl="~/Home/Login"
</authentication>
timeout="2880"/>
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.
Collapse | Copy Code
public ActionResult Login()
{
if ((Request.Form["txtUserName"] == "Shiv") &&
(Request.Form["txtPassword"] == "Shiv@123"))
{
FormsAuthentication.SetAuthCookie("Shiv",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.
Collapse | Copy Code
[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}
How to implement AJAX in MVC?
You can implement AJAX in two ways in MVC:


AJAX libraries
jQuery
Below is a simple sample of how to implement AJAX by using the “AJAX” helper library. In the
below code you can see we have a simple form which is created by using the
Ajax.BeginForm syntax. This form calls a controller action called getCustomer. So now
the submit action click will be an asynchronous AJAX call.
Collapse | Copy Code
<script language="javascript">
function OnSuccess(data1)
{
// Do something here
}
</script>
<div>
<%
var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
%>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" /><br />
<input id="txtCustomerName" type="text" /><br />
<input id="Submit2" type="submit" value="submit"/></div>
<%} %>
In case you want to make AJAX calls on hyperlink clicks, you can use the Ajax.ActionLink
function as shown in the below code.
Figure: Implement AJAX in MVC
So if you want to create an AJAX asynchronous hyperlink by name GetDate which calls the
GetDate function in the controller, below is the code for that. Once the controller responds,
this data is displayed in the HTML DIV tag named DateDiv.
Collapse | Copy Code
<span id="DateDiv" />
<%:
Ajax.ActionLink("Get Date","GetDate",
new AjaxOptions {UpdateTargetId = "DateDiv" })
%>
Below is the controller code. You can see how the GetDate function has a pause of 10 seconds.
Collapse | Copy Code
public class Default1Controller : Controller
{
public string GetDate()
{
Thread.Sleep(10000);
return DateTime.Now.ToString();
}
}
The second way of making an AJAX call in MVC is by using jQuery. In the below code you can
see we are making an AJAX POST call to a URL /MyAjax/getCustomer. This is done by using
$.post. All this logic is put into a function called GetData and you can make a call to the
GetData function on a button or a hyperlink click event as you want.
Collapse | Copy Code
function GetData()
{
var url = "/MyAjax/getCustomer";
$.post(url, function (data)
{
$("#txtCustomerCode").val(data.CustomerCode);
$("#txtCustomerName").val(data.CustomerName);
}
)
}
What kind of events can be tracked in AJAX?
Figure: Tracked in AJAX
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 you are
returning different types of views dynamically, ActionResult is the best thing. For
example in the below code snippet, you can see we have a simple action called
DynamicView. Depending on the flag (IsHtmlView) it will either return a
ViewResult or JsonResult.
Collapse | Copy Code
public ActionResult DynamicView()
{
if (IsHtmlView)
return View(); // returns simple ViewResult
else
return Json(); // returns JsonResult view
}
What are the different types of results in MVC?
Note: It’s difficult to remember all the 12 types. But some important ones you can remember for
the interview are ActionResult, ViewResult, and JsonResult. Below is a detailed list
for your interest:
There 12 kinds of results in MVC, at the top is the ActionResult class which is a base class
that can have 11 subtypes 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
6. JsonResult - Serializes a given ViewData object to JSON format
7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the
client
8. ContentResult - Writes content to the response stream without requiring a view
9. FileContentResult - Returns a file to the client
10. FileStreamResult - Returns a file to the client, which is provided by a Stream
11. FilePathResult - Returns a file to the client
1.
2.
3.
4.
5.
What are ActionFilters in MVC?
ActionFilters help you to perform logic while an MVC action is executing or after an MVC
action has executed.
Figure: ActionFilters in MVC
Action filters are useful in the following scenarios:
1.
2.
3.
4.
Implement post-processing logic before the action happens.
Cancel a current execution.
Inspect the returned value.
Provide extra data to the action.
You can create action filters by two ways:


Inline action filter.
Creating an ActionFilter attribute.
To create an inline action attribute we need to implement the IActionFilter interface. The
IActionFilter interface has two methods: OnActionExecuted and
OnActionExecuting. We can implement pre-processing logic or cancellation logic in these
methods.
Collapse | Copy Code
public class Default1Controller : Controller , IActionFilter
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
void IActionFilter.OnActionExecuted(ActionExecutedContext
filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext
filterContext)
{
Trace.WriteLine("Action is executing");
}
}
The problem with the inline action attribute is that it cannot be reused across controllers. So we
can convert the inline action filter to an action filter attribute. To create an action filter attribute
we need to inherit from ActionFilterAttribute and implement the IActionFilter
interface as shown in the below code.
Collapse | Copy Code
public class MyActionAttribute : ActionFilterAttribute ,
IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext
filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext
filterContext)
{
Trace.WriteLine("Action executing");
}
}
Later we can decorate the controllers on which we want the action attribute to execute. You can
see in the below code I have decorated the Default1Controller with the
MyActionAttribute class which was created in the previous code.
Collapse | Copy Code
[MyActionAttribute]
public class Default1Controller : Controller
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
}
Can we create our custom view engine using MVC?
Yes, we can create our own custom view engine in MVC. To create our own custom view engine
we need to follow three steps:
Let’ say we want to create a custom view engine where in the user can type a command like
“<DateTime>” and it should display the current date and time.
Step 1: We need to create a class which implements the IView interface. In this class we should
write the logic of how the view will be rendered in the render function. Below is a simple code
snippet for that.
Collapse | Copy Code
public class MyCustomView : IView
{
private string _FolderPath; // Define where
stored
public string FolderPath
{
get { return _FolderPath; }
set { _FolderPath = value; }
}
our views are
public void Render(ViewContext viewContext,
System.IO.TextWriter writer)
{
// Parsing logic <dateTime>
// read the view file
string strFileData = File.ReadAllText(_FolderPath);
// we need to and replace <datetime> datetime.now value
string strFinal = strFileData.Replace("<DateTime>",
DateTime.Now.ToString());
// this replaced data has to sent for display
writer.Write(strFinal);
}
}
Step 2: We need to create a class which inherits from
VirtualPathProviderViewEngine and in this class we need to provide the folder path
and the extension of the view name. For instance, for Razor the extension is “cshtml”; for aspx,
the view extension is “.aspx”, so in the same way for our custom view, we need to provide an
extension. Below is how the code looks like. You can see the ViewLocationFormats is set
to the Views folder and the extension is “.myview”.
Collapse | Copy Code
public class MyViewEngineProvider :
VirtualPathProviderViewEngine
{
// We will create the object of Mycustome view
public MyViewEngineProvider() // constructor
{
// Define the location of the View file
this.ViewLocationFormats = new string[] {
"~/Views/{1}/{0}.myview",
"~/Views/Shared/{0}.myview" }; //location and
extension of our views
}
protected override IView CreateView(
ControllerContext controllerContext, string viewPath,
string masterPath)
{
var physicalpath =
controllerContext.HttpContext.Server.MapPath(viewPath);
MyCustomView obj = new MyCustomView(); // Custom view
engine class
obj.FolderPath = physicalpath; // set the path where the
views will be stored
return obj; // returned this view paresing
// logic so that it can be registered in the view engine
collection
}
protected override IView CreatePartialView(ControllerContext
controllerContext, string partialPath)
{
var physicalpath =
controllerContext.HttpContext.Server.MapPath(partialPath);
MyCustomView obj = new MyCustomView(); // Custom view
engine class
obj.FolderPath = physicalpath; // set the path where the
views will be stored
return obj;
// returned this view paresing logic
// so that it can be registered in the view engine
collection
}
}
Step 3: We need to register the view in the custom view collection. The best place to register the
custom view engine in the ViewEngines collection is the global.asax file. Below is the code
snippet for that.
Collapse | Copy Code
protected void Application_Start()
{
// Step3 :- register this object in the view engine
collection
ViewEngines.Engines.Add(new MyViewEngineProvider());
…..
}
Below is a simple output of the custom view written using the commands defined at the top.
Figure: Custom view engine using MVC
If you invoke this view, you should see the following output:
How to send result back in JSON format in MVC
In MVC, we have the JsonResult class by which we can return back data in JSON format.
Below is a simple sample code which returns back a Customer object in JSON format using
JsonResult.
Collapse | Copy Code
public JsonResult getCustomer()
{
Customer obj = new Customer();
obj.CustomerCode = "1001";
obj.CustomerName = "Shiv";
return Json(obj,JsonRequestBehavior.AllowGet);
}
Below is the JSON output of the above code if you invoke the action via the browser.
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.
But WCF SOAP also does the same thing, so how does WebAPI differ?
SOAP
Heavy weight because of
complicated WSDL
Size
structure.
Protocol Independent of protocols.
To parse SOAP message,
the client needs to
understand WSDL format.
Writing custom code for
parsing WSDL is a heavy
Formats 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-*
Principles
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. (Please refer to
REST in WCF chapter.)
With WCF you can implement REST, so why WebAPI?
WCF was brought into implement SOA, the intention was never to implement REST. WebAPI is
built from scratch and the only goal is to create HTTP services using REST. Due to the one point
focus for creating REST service, WebAPI is more preferred.
How to implement WebAPI in MVC
Below are the steps to implement WebAPI:
Step 1: Create the project using the WebAPI template.
Figure: Implement WebAPI in MVC
Step 2: Once you have created the project you will notice that the controller now inherits from
ApiController and you can now implement POST, GET, PUT, and DELETE methods of
the HTTP protocol.
Collapse | Copy Code
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
Step 3: If you make an HTTP GET call you should get the below results:
Figure: HTTP
How can we detect that an MVC controller is called by POST or GET?
To detect if the call on the controller is a POST action or a GET action we can use the
Request.HttpMethod property as shown in the below code snippet.
Collapse | Copy Code
public ActionResult SomeAction()
{
if (Request.HttpMethod == "POST")
{
return View("SomePage");
}
else
{
return View("SomeOtherPage");
}
}
What is bundling and minification in MVC?
Bundling and minification helps us improve request load times of a page thus increasing
performance.
How does bundling increase performance?
Web projects always need CSS and script files. Bundling helps us combine multiple JavaScript
and CSS files in to a single entity thus minimizing multiple requests in to a single request.
For example consider the below web request to a page . This page consumes two JavaScript files
Javascript1.js and Javascript2.js. So when this is page is requested it makes three request calls:


One for the Index page.
Two requests for the other two JavaScript files: Javascript1.js and Javascript2.js.
The below scenario can become worse if we have a lot of JavaScript files resulting in multiple
requests, thus decreasing performance. If we can somehow combine all the JS files into a single
bundle and request them as a single unit that would result in increased performance (see the next
figure which has a single request).
So how do we implement bundling in MVC?
Open BundleConfig.cs from the App_Start folder.
In BundleConfig.cs, add the JS files you want bundle into a single entity in to the bundles
collection. In the below code we are combining all the javascript JS files which exist in the
Scripts folder as a single unit in to the bundle collection.
Collapse | Copy Code
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js"));
Below is how your BundleConfig.cs file will look like:
Collapse | Copy Code
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new
ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js"));
BundleTable.EnableOptimizations = true;
}
}
Once you have combined your scripts into one single unit we then to include all the JS files into
the view using the below code. The below code needs to be put in the ASPX or Razor view.
Collapse | Copy Code
<%= Scripts.Render("~/Scripts/MyScripts")
%>
If you now see your page requests you would see that script request is combined into one
request.
How can you test bundling in debug mode?
If you are in a debug mode you need to set EnableOptimizations to true in the
bundleconfig.cs file or else you will not see the bundling effect in the page requests.
Collapse | Copy Code
BundleTable.EnableOptimizations = true;
Explain minification and how to implement it
Minification reduces the size of script and CSS files by removing blank spaces , comments etc.
For example below is a simple javascript code with comments.
Collapse | Copy Code
// This is test
var x = 0;
x = x + 1;
x = x * 2;
After implementing minification the JavaScript code looks like below. You can see how
whitespaces and comments are removed to minimize file size, thus increasing performance.
Collapse | Copy Code
var x=0;x=x+1;x=x*2;
How do we implement minification?
When you implement bundling, minification is implemented by itself. In other words the steps to
implement bundling and minification are the same.
Explain Areas in MVC?
Areas help you to group functionalities in to independent modules thus making your project
more organized. For example in the below MVC project we have four controller classes and as
time passes by if more controller classes are added it will be difficult to manage. In bigger
projects you will end up with 100’s of controller classes making life hell for maintenance.
If we can group controller classes in to logical section like “Invoicing” and “Accounting” that
would make life easier and that’s what “Area” are meant to.
You can add an area by right clicking on the MVC solution and clicking on “Area” menu as
shown in the below figure.
In the below image we have two “Areas” created “Account” and “Invoicing” and in that I have
put the respective controllers. You can see how the project is looking more organized as
compared to the previous state.
Explain the concept of View Model in MVC?
A view model is a simple class which represents data to be displayed on the view.
For example below is a simple customermodel object with “CustomerName” and “Amount”
property.
Collapse | Copy Code
CustomerViewModel obj = new CustomerViewModel();
obj.Customer.CustomerName = "Shiv";
obj.Customer.Amount = 1000;
But when this “Customer” model object is displayed on the MVC view it looks something as
shown in the below figure. It has “CustomerName” , “Amount” plus “Customer Buying Level”
fields on the view / screen. “Customer buying Level” is a color indicationwhich indicates how
aggressive the customer is buying.
“Customer buying level” color depends on the value of the “Amount property. If the amount is
greater than 2000 then color is red , if amount is greater than 1500 then color is orange or else
the color is yellow.
In other words “Customer buying level” is an extra property which is calculated on the basis of
amount.
So the Customer viewmodel class has three properties



“TxtCustomerName” textbox takes data from “CustomerName” property as it is.
“TxtAmount” textbox takes data from “Amount” property of model as it is.
“CustomerBuyingLevelColor” displays color value depending on the “Amount “ value.
Customer Model
CustomerName
Customer ViewModel
TxtCustomerName
Amount
TxtAmount
CustomerBuyingLevelColor
What kind of logic view model class will have?
As the name says view model this class has the gel code or connection code which connects the
view and the model.
So the view model class can have following kind of logics:



Color transformation logic: - For example you have a “Grade” property in model and
you would like your UI to display “red” color for high level grade, “yellow” color for low
level grade and “green” color of ok grade.
Data format transformation logic :-Your model has a property “Status” with “Married”
and “Unmarried” value. In the UI you would like to display it as a checkbox which is
checked if “married” and unchecked if “unmarried”.
Aggregation logic: -You have two differentCustomer and Address model classes and
you have view which displays both “Customer” and “Address” data on one go.
Structure downsizing: - You have “Customer” model with “customerCode” and
“CustomerName” and you want to display just “CustomerName”. So you can create a
wrapper around model and expose the necessary properties.
How can we use two ( multiple) models with a single view?
Let us first try to understand what the interviewer is asking. When we bind a model with
a view we use the model dropdown as shown in the below figure. In the below figure we
can only select one model.
But what if we want to bind “Customer” as well as “Order” class to the view.
For that we need to create a view model which aggregates both the classes as shown in
the below code. And then bind that view model with the view.
Collapse | Copy Code
public class CustOrderVM
{
public Customer cust = new Customer();
public Order Ord = new Order();
}
In the view we can refer both the model using the view model as shown in the below
code.
Collapse | Copy Code
<%= 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 anddisplay mode will handle the rest.
For example we can create a view “Home.aspx” which will render for the desktop
computers and Home.Mobile.aspx for mobile devices. Now when an end user sends a
request to the MVC application, display mode checks the “user agent” headers and
renders the appropriate view to the device accordingly.
Explain MVC model binders?
Model binder maps HTML form elements to the model. It acts like a bridge between
HTML UI and MVC model. Many times HTML UI names are different than the model
property names. So in the binder we can write the mapping logic between the UI and the
model.
Explain the concept of MVC Scaffolding?
Collapse | Copy Code
Note :- Do not get scared with the word. Its actually a
very simple thing.
Scaffolding is a technique in which the MVC template helps to auto-generate CRUD
code. CRUD stands for create, read, update and delete.
So to generate code using scaffolding technique we need to select one of the types of
templates (leave the empty one).
For instance if you choose “using Entity framework” template the following code is
generated.
It creates controller code, view and also table structure as shown in the below figure.
What does scaffolding use internally to connect to database?
It uses Entity framework internally.
How can we do exception handling in MVC?
In the controller you can override the “OnException” event and set the “Result” to the
view name which you want to invoke when error occurs. In the below code you can see
we have set the “Result” to a view named as “Error”.
We have also set the exception so that it can be displayed inside the view.
Collapse | Copy Code
public class HomeController : Controller
{
protected override void
OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
var model = new
HandleErrorInfo(filterContext.Exception,
"Controller","Action");
filterContext.Result = new ViewResult()
{
ViewName = "Error",
ViewData = new ViewDataDictionary(model)
};
}
}
1. What is main objective of ASP.NET MVC 4 or What is new in MVC4 ?
Ans.




Easy Mobile web applications (ASP.NET MVC 4 complete focus on Mobile
application development)
Full HTML5 support
ASP.NET MVC web application with cloud support
Working with different mobile and desktop web browsers
Description.
The main objective of ASP.NET MVC 4 is making to develop mobile web applications
easily.Other than mobile web applications It’s focus is also on better HTML5 support and
making ASP.NET MVC web application cloud ready.
By using new features of ASP.NET MVC 4 you can develop web applications that can work
well across different desktop web browsers and mobile devices.
2. What is Web API ‘s in Asp.Net MVC 4 ?
Ans.



Web API is a new framework for consuming & building HTTP Services.
Web API supports wide range of clients including different browsers and mobile devices.
It is very good platform for developing RESTful services since it talk’s about HTTP.
3. What is the use of web API ? Why Web API needed, If you have already RESTful
services using WCF ?
Ans. 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 needs lot of config settings, URI
templates, contract’s & endpoints which developing RESTful services using web API is
simple.
4. What are the new enhancements done in default project template of ASP.NET MVC 4?
Ans.


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 need of any kind of additional customization.
5. 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) ?
Ans.

Smart Phones & tablets touch got smart by using new jQuery.Mobile.MVC NuGet
pacage.
The mobile project template touch optimized UI by using jQuery.Mobile.MVC NuGet Package
for tablets and smart phones.
6. What is the use of Display Modes?
Ans.

View can be changed automatically based on browser(For mobile and desktop browser’s)
Display Modes is newly added feature in ASP.NET MVC 4. Views selected automatically by
application depending on the browser. Example: If a desktop browser requests login page of an
application it will return Views\Account\Login.cshtml view & if a mobile browser requests
home page it will return Views\Account\Login.mobile.cshtml view.
7. What are the main features of ASP.NET MVC 4 used by ASP.NET Web API?
Ans.


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 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.
8. What are Bundling & Minification features in ASP.NET MVC 4?
Ans. Bundling & Minification reduces number of HTTP requests. Bundling & Minification
combines individual files into single. Bundled file for CSS & scripts and then it reduce’s overall
size by minifying the contents of the bundle.
9 . What are the difference between asynchronous controller implementation b/w ASP.NET
MVC 3 & ASP.NET MVC 4? Can you explain in detail?
Ans. There is major difference is on 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 to declare 2 action method. One can serve the purpouse.
MVC 4 using .Net Framework 4.5 support for asynchronous communication.
10. Is MVC 4 supporting Windows Azure SDK (Software Development Kit) ?
Ans. Yes, MVC 4 is supporting Windows Azure SDK version 1.6 or higher.
Interface and abstract :
1) C# doesn't support Multiple inheritance ( means deriving a class from more than one
class)... If your application supposed to have more than one class features at a time, we
can inherit one class and other interface as follows:
Public class ChildClass : BaseClass, BaseInterface
{
}
2) An abstract class can have shared state or functionality. An interface is only a promise
to provide the state or functionality. A good abstract class will reduce the amount of
code that has to be rewritten because it's functionality or state can be shared. The
interface has no defined information to be shared
Point to Remember
Abstract class
A class that cannot be instantiated. An abstract class is a class
that must be inherited and have the methods overridden. An abstract
class is essentially a blueprint for a class without any
implementation.
An abstract class is a special kind of class that cannot be
instantiated. It normally contains one or more abstract methods or
abstract properties. It provides body to a class.
Interface
An interface has no implementation; it only has the signature or in
other words, just the definition of the methods without the body.
It's an abstract class with public abstract methods all of which must
be implemented in the inherited classes.
In which Scenario you will go for Interface or Abstract Class?
Interfaces, like classes, define a set of properties, methods, and
events. But unlike classes, interfaces do not provide implementation.
They are implemented by classes, and defined as separate entities from
classes. Even though class inheritance allows your classes to inherit
implementation from a base class, it also forces you to make most of
your design decisions when the class is first published.
Abstract classes are useful when creating components because they
allow you specify an invariant level of functionality in some methods,
but leave the implementation of other methods until a specific
implementation of that class is needed. They also version well,
because if additional functionality is needed in derived classes, it
can be added to the base class without breaking code.
Difference Abstract class vs Interface
Abstract Class:1) An abstract method is created by specifying the abstract type
modifier.
2) An abstract method contains no body.
3) An abstract method is not implemented by the base class.
4) An abstract method is automatically virtual.
5) A derived class must override it.
6) Abstract class can have modifiers for methods,properties etc.,
7) An abstract class can implement a property.
8) The abstract modifier cannot be applied to static methods.
9) Properties can also be abstract.
10) A class containing abstract methods must be declared as abstract
with the abstract specifier.
11) There can be no objects of an abstract class.
12) If a derived class doesn't implement all of the abstract methods
in the base class, then the derived class must also
be specified
as abstract.
13) An abstract class can inherit from a class and one or more
interfaces.
14) An abstract class can implement code with non-Abstract methods.
15) Abstract class can have constant and fields.
16) An abstract class can have constructors or destructor's.
17) An abstract class cannot be inherited from by structures.
18) An abstract class cannot support multiple inheritance.
19) 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.
Interface:1) Interfaces cannot be instantiated directly.
2) Interfaces can contain events, method, indexer and properties.
3) An Interface can contain property definitions.
4) Interfaces contain no implementation of methods.
5) Classes and Structs can implement more than one interface.
6) An Interface can be inherited from by structures.
7) An interface itself can inherit from multiple interfaces (Interface
can support multiple
inheritance).
8) An abstract class can implement a property.
9) 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.
Similarity:
Abstract and Interfaces can’t be instantiated directly.
Like interfaces abstract class can also be declarative, if all members define abstract
Differences:
Abstract class may or may not have abstract method other than interfaces only declarative.
Abstract class can contain variable other than interface can’t.
Interfaces members are implicitly public; so you can’t use access modifiers to restrict access
other than abstract class follows the general class rules.
We can’t use static and constant members in interface other than abstract class we can use.
A Class or Struct can be inherited from multiple interfaces but only from single abstract class.
1. What is C#?
C# is an object oriented, type safe and managed language that is compiled by .Net framework to
generate Microsoft Intermediate Language.
3. Can multiple catch blocks be executed?
No, Multiple catch blocks can’t be executed. Once the proper catch code executed, the control is
transferred to the finally block and then the code that follows the finally block gets executed.
4. What is the difference between public, static and void?
All these are access modifiers in C#. Public declared variables or methods are accessible
anywhere in the application. Static declared variables or methods are globally accessible without
creating an instance of the class. The compiler stores the address of the method as the entry point
and uses this information to begin execution before any objects are created. And Void is a type
modifier that states that the method or variable does not return any value.
5. What is an object?
An object is an instance of a class through which we access the methods of that class. “New”
keyword is used to create an object. A class that creates an object in memory will contain the
information about the methods, variables and behavior of that class.
6. Define Constructors?
A constructor is a member function in a class that has the same name as its class. The constructor
is automatically invoked whenever an object class is created. It constructs the values of data
members while initializing the class.
7. What is Jagged Arrays?
The array which has elements of type array is called jagged array. The elements can be of
different dimensions and sizes. We can also call jagged array as Array of arrays.
8. What is the difference between ref & out parameters?
An argument passed as ref must be initialized before passing to the method whereas out
parameter needs not to be initialized before passing to a method.
9. What is the use of using statement in C#?
The using block is used to obtain a resource and use it and then automatically dispose of when
the execution of block completed.
10. What is serialization?
When we want to transport an object through network then we have to convert the object into a
stream of bytes. The process of converting an object into a stream of bytes is called Serialization.
For an object to be serializable, it should inherit ISerialize Interface.
De-serialization is the reverse process of creating an object from a stream of bytes.
11. Can “this” be used within a static method?
We can’t use ‘This’ in a static method because we can only use static variables/methods in a
static method.
12. What is difference between constants and read-only?
Constant variables are declared and initialized at compile time. The value can’t be changed after
wards. Read-only variables will be initialized only from the Static constructor of the class. Read
only is used only when we want to assign the value at run time.
13. What is an interface class?
Interface is an abstract class which has only public abstract methods and the methods only have
the declaration and not the definition. These abstract methods must be implemented in the
inherited classes.
14. What are value types and reference types?
Value types are stored in the Stack whereas reference types stored on heap.
Value types:
int, enum , byte, decimal, double
1 int, enum , byte, decimal, double, float, long
Reference Types:
string , class, interface, object
1 string , class, interface, object
15. What are Custom Control and User Control?
Custom Controls are controls generated as compiled code (Dlls), those are easier to use and can
be added to toolbox. Developers can drag and drop controls to their web forms. Attributes can be
set at design time. We can easily add custom controls to Multiple Applications (If Shared Dlls),
If they are private then we can copy to dll to bin directory of web application and then add
reference and can use them.
User Controls are very much similar to ASP include files, and are easy to create. User controls
can’t be placed in the toolbox and dragged – dropped from it. They have their design and code
behind. The file extension for user controls is ascx.
16. What are sealed classes in C#?
We create sealed classes when we want to restrict the class to be inherited. Sealed modifier used
to prevent derivation from a class. If we forcefully specify a sealed class as base class then a
compile-time error occurs.
17. What is method overloading?
Method overloading is creating multiple methods with the same name with unique signatures in
the same class. When we compile, the compiler uses overload resolution to determine the
specific method to be invoke.
18. What is the difference between Array and Arraylist?
In an array, we can have items of the same type only. The size of the array is fixed. An arraylist
is similar to an array but it doesn’t have a fixed size.
19. Can a private virtual method be overridden?
No, because they are not accessible outside the class.
20. Describe the accessibility modifier “protected internal”.
Protected Internal variables/methods are accessible within the same assembly and also from the
classes that are derived from this parent class.
21. What are the differences between System.String and System.Text.StringBuilder
classes?
System.String is immutable. When we modify the value of a string variable then a new memory
is allocated to the new value and the previous memory allocation released. System.StringBuilder
was designed to have concept of a mutable string where a variety of operations can be performed
without allocation separate memory location for the modified string.
22. What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?
Using Clone() method, we creates a new array object containing all the elements in the original
array and using CopyTo() method, all the elements of existing array copies into another existing
array. Both the methods perform a shallow copy.
23. How can we sort the elements of the array in descending order?
Using Sort() methods followed by Reverse() method.
24. Write down the C# syntax to catch exception?
To catch an exception, we use try catch blocks. Catch block can have parameter of
system.Exception type.
Eg:
try
{
GetAllData();
}
1 try
2{
3 GetAllData();
4}
5 catch(Exception ex)
6{
7}
In the above example, we can omit the parameter from catch statement.
25. What’s the difference between an interface and abstract class?
Interfaces have all the methods having only declaration but no definition. In an abstract class, we
can have some concrete methods. In an interface class, all the methods are public. An abstract
class may have private methods.
26. What is the difference between Finalize() and Dispose() methods?
Dispose() is called when we want for an object to release any unmanaged resources with them.
On the other hand Finalize() is used for the same purpose but it doesn’t assure the garbage
collection of an object.
27. What are circular references?
Circular reference is situation in which two or more resources are interdependent on each other
causes the lock condition and make the resources unusable.
28. What are generics in C#.NET?
Generics are used to make reusable code classes to decrease the code redundancy, increase type
safety and performance. Using generics, we can create collection classes. To create generic
collection, System.Collections.Generic namespace should be used instead of classes such as
ArrayList in the System.Collections namespace. Generics promotes the usage of parameterized
types.
29. What is an object pool in .NET?
An object pool is a container having objects ready to be used. It tracks the object that is currently
in use, total number of objects in the pool. This reduces the overhead of creating and re-creating
objects.
30. List down the commonly used types of exceptions in .Net?
ArgumentException, ArgumentNullException , ArgumentOutOfRangeException,
ArithmeticException, DivideByZeroException ,OverflowException ,
IndexOutOfRangeException ,InvalidCastException ,InvalidOperationException ,
IOEndOfStreamException , NullReferenceException , OutOfMemoryException ,
StackOverflowException etc.
31. What are Custom Exceptions?
Sometimes there are some errors that need to be handeled as per user requirements. Custom
exceptions are used for them and are used defined exceptions.
32. What are delegates?
Delegates are same are function pointers in C++ but the only difference is that they are type safe
unlike function pointers. Delegates are required because they can be used to write much more
generic type safe functions.
33. How do you inherit a class into other class in C#?
Colon is used as inheritance operator in C#. Just place a colon and then the class name.
public class DerivedClass : Bas
1 public class DerivedClass : BaseClass
34. What is the base class in .net from which all the classes are derived from?
System.Object
1 System.Object
35. What is the difference between method overriding and method overloading?
In method overriding, we change the method definition in the derived class that changes the
method behavior. Method overloading is creating a method with the same name within the same
class having different signatures.
36. What are the different ways a method can be overloaded?
Methods can be overloaded using different data types for parameter, different order of
parameters, and different number of parameters.
37. Why can’t you specify the accessibility modifier for methods inside the interface?
In an interface, we have virtual methods that do not have method definition. All the methods are
there to be overridden in the derived class. That’s why they all are public.
38. How can we set class to be inherited, but prevent the method from being over-ridden?
Declare the class as public and make the method sealed to prevent it from being overridden.
39. What happens if the inherited interfaces have conflicting method names?
Implement is up to you as the method is inside your own class. There might be problem when the
methods from different interfaces expect different data, but as far as compiler cares you’re okay.
40. What is the difference between a Struct and a Class?
Structs are value-type variables and classes are reference types. Structs stored on the stack,
causes additional overhead but faster retrieval. Structs cannot be inherited.
41. How to use nullable types in .Net?
Value types can take either their normal values or a null value. Such types are called nullable
types.
Int? someID = null;
If(someID.HasVAlue)
{
}
1 Int? someID = null;
2 If(someID.HasVAlue)
3{
4}
42. How we can create an array with non-default values?
We can create an array with non-default values using Enumerable.Repeat.
43. What is difference between is and as operators in c#?
“is” operator is used to check the compatibility of an object with a given type and it returns the
result as Boolean.
“as” operator is used for casting of object to a type or a class.
44. What’s a multicast delegate?
A delegate having multiple handlers assigned to it is called multicast delegate. Each handler is
assigned to a method.
45. What are indexers in C# .NET?
Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the
same way as array.
Eg:
public int this[int index]
// Index
1 public int this[int index] // Indexer declaration
46. What is difference between the “throw” and “throw ex” in .NET?
“Throw” statement preserves original error stack whereas “throw ex” have the stack trace from
their throw point. It is always advised to use “throw” because it provides more accurate error
information.
47. What are C# attributes and its significance?
C# provides developers a way to define declarative tags on certain entities eg. Class, method etc.
are called attributes. The attribute’s information can be retrieved at runtime using Reflection.
48. How to implement singleton design pattern in C#?
In singleton pattern, a class can only have one instance and provides access point to it globally.
Eg:
Public sealed class Singleton
{
Private static readonly Singleton
}
1 Public sealed class Singleton
2{
3 Private static readonly Singleton _instance = new Singleton();
4}
49. What is the difference between directcast and ctype?
DirectCast is used to convert the type of an object that requires the run-time type to be the same
as the specified type in DirectCast.
Ctype is used for conversion where the conversion is defined between the expression and the
type.
50. Is C# code is managed or unmanaged code?
C# is managed code because Common language runtime can compile C# code to Intermediate
language.
. What is ASP.Net?
It is a framework developed by Microsoft on which we can develop new generation web sites
using web forms(aspx), MVC, HTML, Javascript, CSS etc. Its successor of Microsoft Active
Server Pages(ASP). Currently there is ASP.NET 4.0, which is used to develop web sites. There
are various page extensions provided by Microsoft that are being used for web site development.
Eg: aspx, asmx, ascx, ashx, cs, vb, html, xml etc.
2. What’s the use of Response.Output.Write()?
We can write formatted output using Response.Output.Write().
3. In which event of page cycle is the ViewState available?
After the Init() and before the Page_Load().
4. What is the difference between Server.Transfer and Response.Redirect?
In Server.Transfer page processing transfers from one page to the other page without making a
round-trip back to the client’s browser. This provides a faster response with a little less overhead
on the server. The clients url history list or current url Server does not update in case of
Server.Transfer.
Response.Redirect is used to redirect the user’s browser to another page or site. It performs trip
back to the client where the client’s browser is redirected to the new page. The user’s browser
history list is updated to reflect the new address.
5. From which base class all Web Forms are inherited?
Page class.
6. What are the different validators in ASP.NET?
1.
2.
3.
4.
5.
6.
Required field Validator
Range Validator
Compare Validator
Custom Validator
Regular expression Validator
Summary Validator
7. Which validator control you use if you need to make sure the values in two different
controls matched?
Compare Validator control.
8. What is ViewState?
ViewState is used to retain the state of server-side objects between page post backs.
9. Where the viewstate is stored after the page postback?
ViewState is stored in a hidden field on the page at client side. ViewState is transported to the
client and back to the server, and is not stored on the server or any other external source.
10. How long the items in ViewState exists?
They exist for the life of the current page.
11. What are the different Session state management options available in ASP.NET?
1. In-Process
2. Out-of-Process.
In-Process stores the session in memory on the web server.
Out-of-Process Session state management stores data in an external server. The external server
may be either a SQL Server or a State Server. All objects stored in session are required to be
serializable for Out-of-Process state management.
12. How you can add an event handler?
Using the Attributes property of server side control.
e.g.
btnSubmit.Attributes.Add("onMo
1 btnSubmit.Attributes.Add("onMouseOver","JavascriptCode();")
13. What is caching?
Caching is a technique used to increase performance by keeping frequently accessed data or files
in memory. The request for a cached file/data will be accessed from cache instead of actual
location of that file.
14. What are the different types of caching?
ASP.NET has 3 kinds of caching :
1. Output Caching,
2. Fragment Caching,
3. Data Caching.
15. Which type if caching will be used if we want to cache the portion of a page instead of
whole page?
Fragment Caching: It caches the portion of the page generated by the request. For that, we can
create user controls with the below code:
<%@ OutputCache Duration="1
1 <%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>
16. List the events in page life cycle.
1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad
5) Page_Load
6) Page_LoadComplete
7) Page_PreRender
8)Render
17. Can we have a web application running without web.Config file?
Yes
18. Is it possible to create web application with both webforms and mvc?
Yes. We have to include below mvc assembly references in the web forms application to create
hybrid application.
System.Web.Mvc
System.Web.Razor
1 System.Web.Mvc
2
3 System.Web.Razor
4
5 System.ComponentModel.DataAnnotations
19. Can we add code files of different languages in App_Code folder?
No. The code files must be in same language to be kept in App_code folder.
20. What is Protected Configuration?
It is a feature used to secure connection string information.
21. Write code to send e-mail from an ASP.NET application?
MailMessage mailMess = new M
mailMess.From = "abc@gmail.co
mailMess.To = "xyz@gmail.com
mailMess.Subject = "Test email"
1 MailMessage mailMess = new MailMessage ();
2 mailMess.From = "abc@gmail.com";
3 mailMess.To = "xyz@gmail.com";
4 mailMess.Subject = "Test email";
5 mailMess.Body = "Hi This is a test mail.";
6 SmtpMail.SmtpServer = "localhost";
7 SmtpMail.Send (mailMess);
MailMessage and SmtpMail are classes defined System.Web.Mail namespace.
22. How can we prevent browser from caching an ASPX page?
We can SetNoStore on HttpCachePolicy object exposed by the Response object’s Cache
property:
Response.Cache.SetNoStore ()
Response.Write (DateTime.Now
1 Response.Cache.SetNoStore ();
2 Response.Write (DateTime.Now.ToLongTimeString ());
23. What is the good practice to implement validations in aspx page?
Client-side validation is the best way to validate data of a web page. It reduces the network
traffic and saves server resources.
24. What are the event handlers that we can have in Global.asax file?
Application Events: Application_Start , Application_End, Application_AcquireRequestState,
Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest,
Application_Disposed, Application_EndRequest, Application_Error,
Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute,
Application_PreSendRequestContent, Application_PreSendRequestHeaders,
Application_ReleaseRequestState, Application_ResolveRequestCache,
Application_UpdateRequestCache
Session Events: Session_Start,Session_End
25. Which protocol is used to call a Web service?
HTTP Protocol
26. Can we have multiple web config files for an asp.net application?
Yes.
27. What is the difference between web config and machine config?
Web config file is specific to a web application where as machine config is specific to a machine
or server. There can be multiple web config files into an application where as we can have only
one machine config file on a server.
28. Explain role based security ?
Role Based Security used to implement security based on roles assigned to user groups in the
organization.
Then we can allow or deny users based on their role in the organization. Windows defines
several built-in groups, including Administrators, Users, and Guests.
<AUTHORIZATION>< authorizat
< allow roles="Domain_Name\A
< deny users="*" / >
< /authorization >
1 <AUTHORIZATION>< authorization >
2 < allow roles="Domain_Name\Administrators" / > < !-- Allow Administrators in domain. -- >
3 < deny users="*" / >
< !-- Deny anyone else. -- >
4 < /authorization >
29. What is Cross Page Posting?
When we click submit button on a web page, the page post the data to the same page. The
technique in which we post the data to different pages is called Cross Page posting. This can be
achieved by setting POSTBACKURL property of the button that causes the postback.
Findcontrol method of PreviousPage can be used to get the posted values on the page to which
the page has been posted.
30. How can we apply Themes to an asp.net application?
We can specify the theme in web.config file. Below is the code example to apply theme:
<configuration>
<system.w eb>
1 <configuration>
2
3 <system.web>
4
5 <pages theme="Windows7" />
6
7 </system.web>
8
9 </configuration>
31. What is RedirectPermanent in ASP.Net?
RedirectPermanent Performs a permanent redirection from the requested URL to the specified
URL. Once the redirection is done, it also returns 301 Moved Permanently responses.
32. What is MVC?
MVC is a framework used to create web applications. The web application base builds
on Model-View-Controller pattern which separates the application logic from UI, and the input
and events from the user will be controlled by the Controller.
33. Explain the working of passport authentication.
First of all it checks passport authentication cookie. If the cookie is not available then the
application redirects the user to Passport Sign on page. Passport service authenticates the user
details on sign on page and if valid then stores the authenticated cookie on client machine and
then redirect the user to requested page
34. What are the advantages of Passport authentication?
All the websites can be accessed using single login credentials. So no need to remember login
credentials for each web site.
Users can maintain his/ her information in a single location.
35. What are the asp.net Security Controls?

<asp:Login>: Provides a standard login capability that allows the users to enter their
credentials




<asp:LoginName>: Allows you to display the name of the logged-in user
<asp:LoginStatus>: Displays whether the user is authenticated or not
<asp:LoginView>: Provides various login views depending on the selected template
<asp:PasswordRecovery>: email the users their lost password
36. How do you register JavaScript for webcontrols ?
We can register javascript for controls using <CONTROL name>Attribtues.Add(scriptname,scripttext) method.
37. In which event are the controls fully loaded?
Page load event.
38. what is boxing and unboxing?
Boxing is assigning a value type to reference type variable.
Unboxing is reverse of boxing ie. Assigning reference type variable to value type variable.
39. Differentiate strong typing and weak typing
In strong typing, the data types of variable are checked at compile time. On the other hand, in
case of weak typing the variable data types are checked at runtime. In case of strong typing, there
is no chance of compilation error. Scripts use weak typing and hence issues arises at runtime.
40. How we can force all the validation controls to run?
The Page.Validate() method is used to force all the validation controls to run and to perform
validation.
41. List all templates of the Repeater control.


ItemTemplate
AlternatingltemTemplate



SeparatorTemplate
HeaderTemplate
FooterTemplate
42. List the major built-in objects in ASP.NET?







Application
Request
Response
Server
Session
Context
Trace
43. What is the appSettings Section in the web.config file?
The appSettings block in web config file sets the user-defined values for the whole application.
For example, in the following code snippet, the specified ConnectionString section is used
throughout the project for database connection:
<em><configuration>
<appSettings>
<add key="ConnectionString" va
</appSettings></em>
1 <em><configuration>
2 <appSettings>
3 <add key="ConnectionString" value="server=local; pwd=password; database=default" />
4 </appSettings></em>
44. Which data type does the RangeValidator control support?
The data types supported by the RangeValidator control are Integer, Double, String, Currency,
and Date.
45. What is the difference between an HtmlInputCheckBox control and an
HtmlInputRadioButton control?
In HtmlInputCheckBoxcontrol, multiple item selection is possible whereas
in HtmlInputRadioButton controls, we can select only single item from the group of items.
46. Which namespaces are necessary to create a localized application?
System.Globalization
System.Resources
47. What are the different types of cookies in ASP.NET?
Session Cookie – Resides on the client machine for a single session until the user does not log
out.
Persistent Cookie – Resides on a user’s machine for a period specified for its expiry, such as 10
days, one month, and never.
48. What is the file extension of web service?
Web services have file extension .asmx..
49. What are the components of ADO.NET?
The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command, connection.
50. What is the difference between ExecuteScalar and ExecuteNonQuery?
ExecuteScalar returns output value where as ExecuteNonQuery does not return any value but the
number of rows affected by the query. ExecuteScalar used for fetching a single value and
ExecuteNonQuery used to execute Insert and Update statements.
1. What is an ADO.Net?
ADO.Net is commonly termed as ActiveX Data Objects which is a part of .Net Framework.
ADO.Net framework has set of classes which are used to handle data access by connecting with
different databases like SQL, Access, Oracle, etc…
2. What are two important objects of ADO.Net?
There are two important objects of ADO.Net:


DataReader and .
DataSet.
3. What are the namespaces used in ADO.Net to connect to a database?
Following namespaces are used to connect to Database.
o
o
o
The System.Data namespace.
The System.Data.OleDb namespace – A data provider used to access database
such as Access, Oracle, or SQL.
The System.Data.SQLClient namespace – Used to access SQL as the data
provider.
4. What is LINQ?
LINQ is native query language for .NET framework and it is specially designed to support
queries with the .net applications. LINQ can be connected to SQL and MS Access.
5. What are the data providers in ADO.NET framework?
Below Data Providers are used in ADO.NET framework.
1. .NET Framework Data Provider for SQL Server – A Data provider that provides access
to Microsoft SQL Server 7.0 or later version and it uses the System.Data.SqlClient
namespace.
2. .NET Framework Data Provider for OLE DB – A Data Provider that provides access to
any database exposed by using OLE DB and it uses the System.Data.OleDb namespace.
3. .NET Framework Data Provider for ODBC – A Data Provider that provides access to any
databases exposed by using ODBC and It uses the System.Data.Odbc namespace.
4. .NET Framework Data Provider for Oracle – A Data Provider that provides access to
Oracle database 8.1.7 or later versions and it uses the System.Data.OracleClient
namespace.
6. What is DataReader Object?
Datareader is an object of ADO.Net which provides access to data from a specified data source.
It consists of classes which sequentially read data from a data source like Oracle, SQL or Access.
7. What is Dataset Object?
A Dataset is set to be collection of data with a tabular column representation. Each column in the
table represents a variable and the row represents to value of a variable. This Dataset object can
be obtained from the database values.
8. What is object pooling?
Object pooling is nothing but a repository of the objects in memory which can be used later. This
object pooling reduces the load of object creation when it is needed. Whenever there is a need of
object, object pool manager will take the request and serve accordingly.
9. What is connection pooling?
Connection pooling consists of database connection so that the connection can be used or reused
whenever there is request to the database. This pooling technique enhances the performance of
executing the database commands. This pooling definitely reduces our time and effort.
10. What is Data view?
Data view is the representation of data in various formats and it can be requested by the users.
Data can be exposed in different sort orders or filter on the user condition with the help of Data
view. Data Customization is also possible through Data View.
11. What is Data Adapter?
Data Adapter is a part of ADO.NET data provider which acts as a communicator between
Dataset and the Data source. This Data adapter can perform Select, Insert, Update and Delete
operations in the requested data source.
12. What is the use of SqlCommand object?
SQLCommand object that allows user to interact with the database. This object mainly used to
query the database and it can be of different types – Select, Insert, Modify and Delete.
13. What is the difference between ADO and ADO.Net?
ADO works with the connected data whereas ADO.Net works in a disconnected manner. ADO
has main object called Recordset which is used to reference data. But ADO.Net has various
objects to access the database.
ADO allows creating client side cursors whereas ADO.Net deals with both server side and server
side cursors. ADO allows persisting records in XML format and ADO.Net allows to manipulate
data using XML.
14. What are the benefits of ADO.Net?
Following are the benefits of ADO.Net:





Programmability
Maintainability
Interoperability
Performance
Scalability
15. What is the use of connection object?
ADO.Net Connection object is used to establish a connection between application and the data
source. SQL Commands can be executed once this connection has been established. It is
mandatory to close the connection object once data base activities are completed.
16. What are all features of ADO.Net?
Following are the features of ADO.Net:




Data Paging
Bulk Copy Operation
New Data Controls
Datareader’s execute methods.
17. What is the difference between Response.Expires and Reponse.ExpiresAbsolute?
Response.expires property specify the minutes of page in cache from the time, the request has
been served from server.
But Response.ExpiresAbsolute property provides exact time at which the page in cache expires.
Example –
Response.expires – Set to 10 mins and it will stay in cache for 10 mins from time it has been
requested
Response.ExpiresAbsolute – Oct 30 12:20:15. Till this specified time, Page will be in cache.
18. What is boxing and unboxing?
Conversion of value type to reference type is called Boxing and Conversion of reference to value
type is called Unboxing. Boxing and Unboxing are used for type casting from value to reference
type and vice versa.
19. What is the difference between Datareader and Dataset?
Following table gives difference between Datareader and Dataset:
Datareader
Forward only
Connected Recordset
Single table involved
No relationship required
No XML storage
Occupies Less Memory
Read only
Dataset
Loop through Dataset
Disconnected Recordset
Multiple tables involved
Relationship between tables maintained
Can be stored as XML
Occupies More memory
Can do addition / Updation and Deletion
20. Is it possible to edit data in Repeater control?
No, it is not possible to edit data in the Repeater control.
21. What are all components of ADO.Net data provider?
Following are the components of ADO.Net Data provider:







Connection object – Represents connection to the Database
Command object – Used to execute stored procedure and command on Database
ExecuteNonQuery – Executes command but doesn’t return any value
ExecuteScalar – Executes and returns single value
ExecuteReader – Executes and returns result set
DataReader – Forward and read only recordset
DataAdapter – This acts as a bridge between database and a dataset.
22. What are the differences between OLEDB and SQLClient Providers?
OLEDB provider is used to access any database and provides flexibility of changing the database
at any time. SQLClient provider is used to access only SQL Server database but it provides
excellent performance than OLEDB provider while connecting with SQL Server database.
23. What are the different execute methods of Ado.Net?
Following are different execute methods of ADO.Net command object:




ExecuteScalar – Returns single value from the dataset
ExecutenonQuery – Returns resultset from dataset and it has multiple values
ExecuteReader – Forwardonly resultset
ExecuteXMLReader – Build XMLReader object from a SQL Query
24. What are all the commands used with Data Adapter?
DataAdapter is used to retrieve data from a data source .Insertcommand, UpdateCommand and
DeleteCommand are the commands object used in DataAdapter to manage update on the
database.
25. What are all the different methods under sqlcommand?
There are different methods under SqlCommand and they are:





Cancel – Cancel the query
CreateParameter – returns SQL Parameter
ExecuteNonQuery – Executes and does not return result set
ExecuteReader – executes and returns data in DataReader
ExecuteScalar – Executes and returns single value


ExecuteXmlReader – Executes and return data in XMLDataReader object
ResetCommandTimeout – Reset Timeout property
26. What is the difference between Dataset.clone and Dataset.copy?
Dataset.clone object copies structure of the dataset including schemas, relations and constraints.
This will not copy data in the table.
Dataset.copy – Copies both structure and data from the table.
27. What is the difference between Command and CommandBuilder object?
Command is used to execute all kind of queries like DML and DDL. DML is nothing but Insert,
Update and Delete. DDL are like Create and drop tables.
Command Builder object is used to build and execute DML queries like Create and Drop Tables.
28. Is it possible to load multiple tables in a Dataset?
Yes, it is possible to load multiple tables in a single dataset.29. Which provider is used to
connect MS Access, Oracle, etc…?
OLEDB Provider and ODBC Provider are used to connect to MS Access and Oracle. Oracle
Data Provider is also used to connect exclusively for oracle database.
30. Do we use stored procedure in ADO.Net?
Yes, stored procedures are used in ADO.Net and it can be used for common repetitive functions.
31. What are the methods of XML dataset object?
There are various methods of XML dataset object:
GetXml() – Get XML data in a Dataset as a single string.
GetXmlSchema() – Get XSD Schema in a Dataset as a single string.
ReadXml() – Reads XML data from a file.
ReadXmlSchema() – Reads XML schema from a file.
WriteXml() – Writes the contents of Dataset to a file.
WriteXmlSchema() – Writes XSD Schema into a file.
32. What are all the different authentication techniques used to connect to MS SQL
Server?
SQL Server should authenticate before performing any activity in the database. There are two
types of authentication:


Windows Authentication – Use authentication using Windows domain accounts only.
SQL Server and Windows Authentication Mode – Authentication provided with the
combination of both Windows and SQL Server Authentication.
33. What is the use of Dataview?
Dataview is used to represent a whole table or a part of table. It is best view for sorting and
searching data in the data table.
34. What are the Data providers in ADO.Net?
Following are the Data Providers used in ADO.Net:.



MS SQL Server.
OLEDB.
ODBC.
35. Which method is used by command class to execute SQL statements that return single
value?
Execute Scalar method is used by command class to execute SQL statement which can return
single values.
36. Which keyword is used to accept variable number of parameters?
Params keyword is used to accept variable number of parameters.
37. Tom is having XML document and that needs to be read on a daily basis. Which
method of XML object is used to read this XML file?
ReadXML() method is used to read XML file.
38. Which method in OLEDBAdapter is used to populate dataset with records?
Fill Method is used to populate dataset with records.
39. Which object needs to be closed?
OLEDBReader and OLDDBConnection object need to be closed. This will stay in memory if it
is not properly closed.
40. What are different layers of ADO.Net?
There are three different layers of ADO.Net:



Presentation Layer
Business Logic Layer
Database Access Layer
41. What are typed and untyped dataset?
Typed datasets use explicit names and data types for their members but untyped dataset uses
table and columns for their members.
42. How to stop running thread?
Thread.Abort() function stops the thread execution at any time.
43. Which method is used to sort the data in ADO.Net?
Sort() method of GridViewControl is used to sort the data in a datatable.
44. Which object is used to add relationship between two Datatables?
DataRelation object is used to add relationship between two or more datatable objects.
45. Which is the best method to get two values from the database?
ExecuteNonQuery is the best method to get two values from the database.
46. What are all the classes that are available in System.Data Namespace?
Following are the classes that are available in System.Data Namespace:




Dataset.
DataTable.
DataColumn.
DataRow.


DataRelation.
Constraint.
47. What are the uses of Stored Procedure?
Following are uses of Stored Procedure:





Improved Performance.
Easy to use and maintain.
Security.
Less time and effort taken to execute.
Less Network traffic.
48. What is the default Timeout for SqlCommand.CommandTimeout property?
The default timeout of Sqlcommand. CommandTimeout property is 30 Seconds.
49. What are the classes in System.Data.Common Namespace?
There are two classes involved in System.Data.Common Nameapce:.


DataColumnMapping.
DataTableMapping.
50. What is LINQ?
Language Integrated Query or LINQ provides programmers and testers to query data and it uses
strongly type’s queries and results
Download