MVC and JQuery
1)
What is MVC?
MVC is an architectural pattern which separates the
representation and user interaction. It’s divided into three broader
sections, Model, View, and Controller.
Model - Model represents the real world object and provides
data to the View
View - The
View is responsible for the look and feel .ie) Applications User Interface.
Controller - The Controller
is responsible for taking the end user request and loading the appropriate
Model and View.
2) What are the benefits of using MVC?
-
Separation of concerns is
achieved as we are moving the code-behind to a separate class file.
-
It provides better support for
test-driven development (TDD).
-
It uses a
Front Controller pattern
-
It does
not use view state or server-based forms
-
It works well for large teams of
Web developers . Bcoz separation of
concerns.
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.
Html.TextBox("CustomerCode")
Below is “Html.TextBoxFor” code
which creates HTML textbox using the property name ‘CustomerCode” from object
“m”.
Html.TextBoxFor(m
=> m.CustomerCode)
In the same way we have for other
HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.
Routing helps you to define a
URL structure and map the URL with the controller.
Routing module is responsible for mapping incoming
browser requests to particular MVC controller actions.
routes.MapRoute(
"View",
"View/ViewCustomer/{id}",
new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional });
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.
5)
Where is the route
mapping code written?
The route mapping code is
written in the “global.asax” file.
6)
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.
7) How can we navigate from one view to
another using a hyperlink?
By using the ActionLink
method,
@Html.ActionLink("Home","Gotohome")
8)
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.
[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}
9)
How can we
maintain sessions in MVC?
Sessions can be maintained in MVC by three
ways: 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.
·
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.
10)
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.
Once the partial view is created you can then
call the partial view in the main view using the Html.RenderPartial
method.
@Html.RenderPartial("MyView");
11) How can we do validations in MVC?
Doing
validation in MVC is by using data annotations.
Data
annotations are nothing but attributes which can be applied on model
properties.
Ex:
public class Customer
{
[Required(ErrorMessage="Customer code is required")]
public string CustomerCode
{
set;
get;
}
}
To display the
validation error message we need to use the ValidateMessageFor
method which belongs to the Html
helper class.
@Html.TextBoxFor(m => m.CustomerCode)
@Html.ValidationMessageFor(m => m.CustomerCode)
Later in the
controller we can check if the model is proper or not by using the ModelState.IsValid
property and accordingly we can take
actions.
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Customer");
}
}
Using @Html.ValidationSummary() to display all errors.
Other data annotation attributes for
validation in MVC?
StringLength,
RegularExpression, Range etc.
12) What is Razor in MVC?
It’s a light weight view engine. Razor is clean,
lightweight, and syntaxes are easy as compared to ASPX.
13)
How to implement
AJAX in MVC?
You can implement AJAX in two ways in
MVC:
1)
AJAX libraries
2)
jQuery
14)
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.
15)
What are the
different types of results in MVC?
There 12 kinds of results in MVC, at the top is
the ActionResult
class which is a base class that can have 11 subtypes
1.
ViewResult - Renders a specified view to the response stream
2.
PartialViewResult - Renders a specified partial view to the
response stream
3.
EmptyResult - An empty response is returned
4.
RedirectResult - Performs an HTTP redirection to a specified
URL
5.
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
16)
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.
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.
17) What is the ‘page lifecycle’ of an ASP.NET
MVC?
Following process are performed by
ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view
19) What is the significance of
ASP.NET routing?
ASP.NET MVC uses ASP.NET routing, to
map incoming browser requests to controller action methods. ASP.NET Routing
makes use of route table. Route table is created when your web application
first starts. The route table is present in the Global.asax file.
20) How route table is created in
ASP.NET MVC?
When an MVC application first starts,
the Application_Start() method is called. This method, in turn, calls the
RegisterRoutes() method. The RegisterRoutes() method creates the route table.
21)What is the use of the following
default route?
{resource}.axd/{*pathInfo}
This route definition, prevent
requests for the Web resource files such as WebResource.axd or
ScriptResource.axd from being passed to a controller.
22) What is the use of action filters
in an MVC application?
Action Filters allow us to add
pre-action and post-action behavior to controller action methods.
23) What are the different types of
filters, in an asp.net mvc application?
1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters
24) Give an example for
Authorization filters in an asp.net mvc application?
1. RequireHttpsAttribute
2. AuthorizeAttribute
25) Which filter executes first in an
asp.net mvc application?
Authorization filter
26) What filters are executed in the end?
Exception Filters
27) When using aspx view engine, to
have a consistent look and feel, across all pages of the application, we can
make use of asp.net master pages. What is asp.net master pages equivalent, when
using razor views?
To have a consistent look and feel
when using razor views, we can make use of layout pages. Layout pages, reside
in the shared folder, and are named as _Layout.cshtml
28)
AJAX =
Asynchronous JavaScript and XML.
AJAX is the art of exchanging data with a
server, and update parts of a web page – without reloading the whole page.
“AJAX does not refresh or reload the
whole page”.
But, the more perfect answer is – “AJAX is an asynchronous technology where others request are synchronous.”
-
Asynchronous requests
have their advantages
Some of the advantages are,
-
Partial
Rendering of a Complex Page
-
It Looks Fast
-
Reduced Server
Load
Ex:
What is
the difference between asynchronous (AJAX) and synchronous request?
Asynchronous
– Two way communication
synchronous
– One way communication
Asynchronous communication
works much like the postal system: An application creates a message (that’s a
piece of data such as the text String “Order 1000 barrels crude oil”, or an XML
expression), and labels the message with a destination address (that’s typically
the logical name of a “mail box”, and not an IP address). The message is passed
to the messaging middleware system.
Now the sender application
proceeds happily, without needing to wait for the message to be delivered.
Synchronous communication works
much like a phone call. The Receiver (callee) must be available, otherwise the
conversation cannot occur.
29) Differ ASP.NET
Webforms Vs ASP.NET MVC?
ASP.NET Webforms
|
ASP.NET MVC
|
It uses a Page Controller
pattern
|
It uses a Front Controller
pattern
|
More
difficult for Test Driven compare to MVC
|
It provides better support for test-driven
development (TDD).
|
It uses view state on
server-based forms,
|
It does not use view state or server-based forms
|
It works well for small teams
of Web developers
|
It works well for large teams of Web developers . Bcoz separation of concerns.
|
JQuery
is a light weight Java Script library
It mainly helps programmer to reduce lines of code as huge code
written in Java Script, can be done easily with JQuery in few lines.
1) What is jQuery Selectors? Give some
examples.
Ans: Selectors are used in jQuery to find
out DOM elements. Selectors can find the elements via ID, CSS, Element name and
hierarchical position of the element.
Code:
Selector
Example Selects
*
$("*") All
elements
#id $("#lastname") The
element with id=lastname
.class $(".intro") All
elements with class="intro"
element $("p") All
p elements
2) Is window.onload is different
from document.ready()?
- The
window.onload() is Java script function and document.ready() is jQuery event
which are called when page is loaded.
- The difference is that document.ready()
is called after the DOM is loaded without waiting for all the contents to get
loaded. While window.onload() function waits until the contents of page is
loaded.
- Suppose there is very large image on a
page, at that time window.onload() will wait until that image is loaded
totally.
- So while using the window.onlaod()
function the execution will be slow, but the document.ready() will not wait
until the image is loaded.
3) What is Chaining in jQuery?
- Chaining
is very powerful feature of jQuery.
- Chaining means specifying multiple function and/or selectors to an
element.
- Examine the below example
$(document).ready(function(){
$('#mydiv').css('color', 'blue');
$('#mydiv').addClass('myclass');
$('#mydiv').fadeIn('fast');
}
By
using chaining we can write above code as follows
$(document).ready(function(){
$('#mydiv').css('color', 'blue').addClass('myclass').fadeIn('fast');
});
-Advantage
of chaining is that it makes your code simple and simple to manage.
-The execution becomes faster because the code search for the element only
once.
4) What is difference between sorting string array
and sorting numerical array in jQuery?
The
sort method is used to sort any array elements. It sorts the string elements
alphabetically.
For
example
$(document).ready(function(){
var mylist = [ “Apple”,”Orange”,”Banana”];
mylist = mylist.sort();
$(“#mydiv”).html(list.join(“”));
});
It
will give following output
Apple
Banana
Orange
5) What is
difference between prop and attr?
- In jQuery both prop() and attr() function is
used to set/get the value of specified property of an element.
- The difference in both the function is that
attr() returns the default value of the property while the prop() returns
the current value of the property.
For
example
<input
value="My Value" type="text"/>
$('input').prop('value', 'Changed Value');
-.attr('value') will return 'My Value'
-.prop('value') will return 'Changed Value'
6) What is resize() function in jQuery?
The
resize() function is called whenever the browser size is changed. This event
can be only used with $(window).
Syntax:
.resize([event_data],
handler(event_object))
-The
“event_data” is the data to be sent to the handler.
-The “handler(event_object)” is a function to be called each time when the
window is resized.
For
example
$(window).resize(function()
{
$('#message).text('window is resized to ' + $(window).width() + ‘x’ +
$(window).height());
});
Features of Jquery
1. One can easily provide effects and can do animations.
2. Applying / Changing CSS.
3. Cool plugins.
4. Ajax support
5. DOM selection events
6. Event Handling
There are 3 types of selectors in Jquery
1. CSS Selector
2. XPath Selector
3. Custom Selector
Q15. What is the difference between .js and
.min.js?
Ans: jQuery library comes in 2 different versions Production
and Deployment. The deployment version is also known as minified version. So
.min.js is basically the minified version of jQuery library file. Both the
files are same as far as functionality is concerned. but .min.js is quite small
in size so it loads quickly and saves bandwidth.
Q16. Why there are two different version of jQuery
library?
Ans: jQuery library comes in 2 different versions.
1. Production
2. Deployment
The production version is quite useful at development time as
jQuery is open source and if you want to change something then you can make
those changes in production version. But the deployment version is minified
version or compressed version so it is impossible to make changes in it. Because
it is compressed, so its size is very less than the production version which
affects the page load time.
Q26. What are the fastest selectors in jQuery?
Ans: ID and element selectors are the fastest selectors in
jQuery.
Q27. What are the slow selectors in jQuery?
Ans: class selectors are the slow compare to ID and element.
Q33. What is the use of jquery .each() function?
Ans: The $.each()
function is used to iterate over a jQuery
object. The $.each()
function can be used to iterate over any
collection, whether it is an object or an array.
Q62. What are various methods to make ajax request
in jQuery?
Ans: Using below jQuery methods, you can make ajax calls.
·
load()
: Load a piece of html into a container DOM
·
$.getJSON()
: Load JSON with GET method.
·
$.getScript()
: Load a JavaScript file.
·
$.get()
: Use to make a GET call and play extensively with
the response.
·
$.post()
: Use to make a POST call and don't want to load the
response to some container DOM.
·
$.ajax()
: Use this to do something on XHR failures, or to
specify ajax options (e.g. cache: true) on the fly.
Connection Pooling
If more customers log into the database, web servers perform
slowly because of more multiple connections getting opened. To avoid this
problem, we have to use the best feature named "connection pooling".
Connection pooling is the ability of re-use
your connection to the Database. This means if you enable Connection pooling in
the connection object, actually you enable the re-use of the connection to more
than one user.
The connection pooling is enabled by default in
the connection object.
Connection pooling reduces the number of times that new
connections must be opened.
The pooler maintains
ownership of the physical connection.
When a
connection is first opened, a connection pool is created based on an exact
matching algorithm that associates the pool with the connection string in the
connection. Each connection pool is associated with a distinct connection
string. When a new connection is opened, if the connection string is not an
exact match to an existing pool, a new pool is created.
In the
following C# example, three new SqlConnection objects are created, but only two
connection pools are required to manage them. Note that the first and second
connection strings differ by the value assigned for Initial Catalog.
using
(SqlConnection connection = new SqlConnection(
"Integrated Security=SSPI;Initial
Catalog=Northwind"))
{
connection.Open();
// Pool A is created.
}
using
(SqlConnection connection = new SqlConnection(
"Integrated Security=SSPI;Initial
Catalog=pubs"))
{
connection.Open();
// Pool B is created because the
connection strings differ.
}
using
(SqlConnection connection = new SqlConnection(
"Integrated Security=SSPI;Initial
Catalog=Northwind"))
{
connection.Open();
// The connection string matches pool
A.
}
1) Difference
Between Exe and Dll
An
EXE can run independently, whereas DLL will run within an
EXE.
DLL is an in-process file and EXE is an out-process file.
What is Difference between HttpGet
and HttpPost?
What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to enable
communications between clients and servers.
HTTP works as a request-response protocol between a client and
server.
Two commonly used methods for a request-response between a
client and server are: GET and POST.
GET - Requests data from a specified resource
POST - Submits data to be processed to a specified resource
Http GET method
Data
is submitted as a part of url.
Data
is visible to the user as it post as query string.
it
is not secure but fast and quick.
It
use Stack method for passing form variable.
Data
is limited to max length of querystring.
It
is good when you want user to bookmark page.
Http
POST method
Data
is submitted in http request body.
Data
is not visible in the url.
It
is more secure but slower as compared to GET.
It
use heap method for passing form variable
It
can post unlimited form variables.
It
is advisable for sending critical data which should not visible to users.
§ There are mainly
two ways to pass data from one web page to another, using HTTP GET and HTTP POST
method.
§ 1) HTTP GET: In HTTP GET
method data passed through url querystring using name value pair. It’s simpler
and you can troubleshoot any problems simply by looking at the address bar in
your browser because all values passed are displayed there. This is also the
primary weakness of this method. The data being passed is visible and is
limited in size to the maximum length of a request string.(Maximum length of
querystring??? do you know what’s max size??? ….)
§ For example,
http://PatelShailesh.com/get_targetpage.aspx?FirstName=Shailesh&LastName=Patel.
In this example, string after ‘?’ is the querystring. You have to seprate
querystring name value pair by ‘&’ character. So in this example
there are two querystring field one is ‘FirstName’ and another is ‘LastName’
and values are ‘shailesh’ and ‘patel’ respectively.
§ Here’s an example
of what a web server receives when a client makes a GET request:
§ GET
/get_targetpage.aspx?firstname=shailesh&lastname=patel HTTP/1.1
HTTP POST: In HTTP POST request data are embeded in a HTTP
HEADER. So data are NOT visible to end user while you can see the data
passed in HTTP GET method. So if you want to pass sensitive
information/data, you should have to use HTTP POST request. Another advantage
is that you can send larger amounts of information compare to HTTP GET method.
Fundamental
Difference is probably the Visibility -
The HTTPGet protocol creates a query
string of the name-and-value pairs and then appends the query string to the URL
of the script on the server that handles the request. Therefore, you can mark
the request.
The HTTPPost protocol passes the
name-and-value pairs in the body of the HTTP request message.