All posts by Thiyagu

.fadeOut() Effect in Jquery

Description:

The fadeOut( ) method fades out all selected/matched elements by applying the opacity to 0, then setting display to “none” . Finally the optional callback will be triggered after completion of animation.

Syntax

.fadeOut(

[duration ] [easing] [callback] )

Ex : $(“#div”).fadeOut(“slow”);

Duration/speed  It specifies the speed of the fadein. The valuse may be slow, fast and milliseconds. (default value: 400)
Easing  It specifies the easing function to be used for transition (default value: swing).
Callback A function to call once the animation is complete.

Example: Without Option(parameter)

From the below code, the “divFadeBox” been visible on the initial load. After clicking “divButton”  the click event been triggered and the fadeOut() will be executed on the “divFadeBox”. Finally “display:none” will be set to the matched element.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
$("#divButton").click(function () {
$("#divFadeBox").fadeOut();
});
});

</script>
</head>
<body>
</br>
<button id="divButton">Click to fade in boxes</button><br><br>
<div id="divFadeBox" style="width:80px;height:80px;display:none;background-color:blue;"></div>
</body>
</html>

Output:

After clicking the “Click to fade Out boxes” button, then the blue box will be disappear as shown below.

<div id="divFadeBox" style="width: 80px; height: 80px; background-color: blue;"></div>

<div id="divFadeBox" style="width: 80px; height: 80px; display: none; background-color: blue;"></div>

fadeIn() Effect in Jquery

Description:

Display matched elements by fading them to opaque. In simple word, its animates the opacity for the matched elements.

Syntax

.fadeIn(

[duration ] [easing] [callback] )

$(“#div”).fadeIn(“slow”);

Duration/speed  It specifies the speed of the fadein. The valuse may be slow, fast and milliseconds. (default value: 400)
Easing  It specifies the easing function to be used for transition (default value: swing).
Callback A function to call once the animation is complete.

Example: Without Option(parameter)

From the below code, the “divFadeBox” element has been set to display:none. So initially it will not visible during the page load. After clicking “divButton”, the fadeIn() will be executed to the “divFadeBox” element.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
$("#divButton").click(function () {
$("#divFadeBox").fadeIn();
});
});

</script>
</head>
<body>
</br>
<button id="divButton">Click to fade in boxes</button><br><br>
<div id="divFadeBox" style="width:80px;height:80px;display:none;background-color:blue;"></div>
</body>
</html>

Output: 

After clicking “Click to fade in boxes” button, then the blue box will be fadeIn as shown below.

Example : With Option(parameter)

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
$("#divButton").click(function () {
$('#divFadeBox').fadeIn(2000, 'swing', function () {
//Execute(callback) function after animation completed.
$("#divButton").attr('value', 'fadeIn() is now Complete');});
}); 
});

</script>
</head>
<body>
<input id="divButton" type="button" value="Click here to see fadeIn" /><br><br>
<div id="divFadeBox" style="width:80px;height:80px;display:none;background-color:blue;"></div>
</body>
</html>

Output

Before button click

After button click, it will be fade-in with duration of 2000 milli second & swing effect. After fade-in completed, callback method will be executed. Finally “fadein() is now complete” text will be append to the button button as shown below.

$(“#divButton”).attr(‘value’, ‘fadeIn() is now Complete‘);

 

jQuery Effects

jQuery framework provide more flexible way to add more effects on a web page by using in-build methods. jQuery effects can be categorized in to following ways

Short Idea About Jquery Effects:

jQuery Effects provide large number of methods for developing rich web application. Let we discuss about jQuery effect below.

Method Description
hide() hides the selected elements.
show() displays the selected elements.
toggle() shows or hides the matched elements.
fadein() Display the matched elements by fading them to opaque.
fadeout() Hide the matched elements by fading them to transparent.
fadeto() Adjust the opacity of the matched elements.
fadetoggle() shows/hides the selected element. ie., toggles between the fadeIn() and fadeOut().
slidedown() shows the matched elements with sliding motion.
slidetoggle() shows or hides the matched elements with slide. ie., it is used to toggle between the slideUp() and slideDown().
slideup() hides the matched elements with sliding motion.
animate() performs animation for the selected element.
clearQueue() It is used to remove all remaining queued functions from the selected elements.
delay() sets delay execution for all the queued functions on the selected elements.
dequeue() It is used to remove the next function from the queue, and then execute the function.
finish() It stops, removes and complete all queued animation for the selected elements.
queue() Show or manipulate the queue of functions to be executed on the matched elements.
stop() stops the animation on the selected elements.

 

Let us discuss more about effect one by one detailed way in up-coming posts.

Implementing jQuery.ajax() using Jquery

What is JQuery Ajax?

AJAX is standing for Asynchronous JavaScript and XML. It helps us to fetch the information from the server without reloading the page (ie., without refresh)JQuery is a great tool which provides a rich set of AJAX methods to develop great web application. jQuery provides the $.ajax method and several methods to make it easier to work with XHRs across browsers.

$.ajax

We can use the jQuery $.ajax() method in a different ways, let we discuss one by one.

  • we can pass it a configuration object as its argument
  • we can pass it a URL and an optional configuration object

SYNTAX: 

  • $.ajax(url,[options])
  • $.ajax([options])

Option Parameter:

Here i have listed few parameters which is using frequently.

Options Description
accepts The content type sent in the request header that tells the server what kind of response it will accept in return.
async By default, all requests are sent asynchronously. Set it false to make it synchronous.
beforeSend A callback function to be executed before Ajax request is sent.
cache A boolean indicating browser cache. Default is true.
complete A callback function to be executed when request finishes.
contentType A string containing a type of content when sending MIME content to the server.
data A data to be sent to the server. It can be JSON object, string or array.
dataType Type of data that we receiving back from the server.
error A callback function to be executed when the request fails.
headers An object of additional header key/value pairs to send along with request.
isLocal Allow the current environment to be recognized as local.
statusCode A JSON object containing numeric HTTP codes and functions to be called when the response has the corresponding code.
success A callback function to be executed when Ajax request succeeds.
timeout A number value in milliseconds for the request timeout.
type A type of http request for operation e.g. POST, PUT and GET. Default is GET.
url A string containing the URL to which the request is sent.

 

1) we can pass it a configuration object as its argument:

The $.ajax() method offers the ability to specify both success and failure callbacks. It have a felxibility
to take a configuration object, which can be defined separately. This approach make the developer to write reusable code.

var updateSuccessfully = function( obj ) {
$( '#divSuccess').html( "Updated successfully" );
};

var showError = function( req, status, err ) {
console.log( 'Went wrong while performing operation', status, err );
};

var ajaxUpdateRequest = {
url: '/dotnethelpers/UpdateUsers',
dataType: 'json',
success: updateSuccessfully,
error: showError
};

// Initiate the request
$.ajax(ajaxUpdateRequest);

Code Explanation:

updateSuccessfully,showError -: Both are methods created for handling success & error.
ajaxUpdateRequest :  It is declared as a separate method for handling the ajax operation. Inside the code, if it return success then ajax success will call the updateSuccessfully method and showError method when ajax operation fails. This approach make the developer to write reusable code.

2) we can pass it a URL and an optional configuration object

In this type, we can also call the $.ajax() method by passing it a URL and an optional configuration object.
This is very useful if we want to use the default configuration for $.ajax(), or if you want to use the same configuration for several URLs

$.ajax( '/dotnethelpers/UpdateUsers', {
type: 'GET',
dataType: 'json',
success: function( resp ) {
console.log( "Operation Performed Successfully" );
},
error: function( req, status, err ) {
console.log( 'Went wrong while performing operation',, status, err );
}
});

Code Explanation:

In above code, we can take advantage of passing url, type, datatype etc as an parameter. so it can be used by several other method for performing operation with different arguments.

 

jQuery Events Handling

What is Event?

Events are actions that can be used in the application. The events can be bind using jquery methods like .on, .bind,etc.,. Below are the few examples for events

  • Mouse click
  • Mouse over on an Element
  • Key Enter
  • An HTML form submission

When these events are triggered, we can use our own custom function to handle the event. These custom functions called as Event Handlers.

Types of Events:

jQuery provides a number of  shorthand Event methods and each corresponds to a DOM event. 

Event Name Shorthand Method
click .click()
keydown .keydown()
keydown .keypress()
keyup .keyup()
mouseover .mouseover()
mouseout .mouseout()
mouseenter .mouseenter()
mouseleave .mouseleave()
scroll .scroll()
focus .focus()
blur .blur()
resize .resize()

Binding Event Handler :

Let us discuss about event handling with simple examples.

Example 1: Simple event binding

$( “div” ).on( “click”, function() {
alert( “div clicked by user” );
});

Explanation :

In the above example, the method is to handle the click event for the div. If user click the div, then click function will automatically triggered
and alert dialog box will appear with the message “div clicked by user”.

Example 2: Handling more than one events

We can handle more than one event in the single function as shown below. 

$( “div” ).on( “mouseenter mouseleave”, function() {
alert( “User using mouse-enter/leave” );
});

Explanation :

The event will trigger after user mouseover/mouseleave on the div.

New Features in ASP.NET 5 and MVC 6

Microsoft has announced the next generation of ASP.NET on 2014, which is called ASP.NET vNext. It included the versions of MVC6, Web API3, Entity Framework7, cloud optimized and SignalR3.

New Features in ASP.NET 5 and MVC 6

OSX and Linux Support:

Not only window user, Linux and OSX users also now able to run ASP.Net application in their platforms itself. This is very great and happy for the develpers who are best with OSX and linux,who are working with OSX and linux systems for their app development. The developers who are not familiar with Visual Studio, will able to use other development environments such as Sublime Text etc.,

Self Hosting

In MVC5, you could have experimented with self-hosting but, for this you first need to host the application on IIS and, then run it on top of ASP .NET Pipeline. MVC 6 on the other hand can be easily self-hosted as it makes use of flexible pipeline where you get total control over all the components which are a part of the pipeline. It will have mini “CLR” version which is “KLR” in our hosting folder, which will will create a runtime environment for the application to run in any environment.

Unification of MVC and Web API Controllers:

In previous, we have used separate for both Web API Controllers and MVC controllers. Due to this,Web API controller in-herit from System.Web.Http.ApiController base class and MVC controller in-herit from System.web.MVC.Controller base class. Now in ASP.NET MVC 6, these have been merged in a single controller. So we can use both API and MVC controller under Microsoft.AspNet.Mvc.Controller namespace.

Tag Helpers

In ASP.NET MVC5, we have used HTML helpers for manipulation of server side HTML elements in Razor view but in ASP.NET MVC 6 introduced Tag helpers instead of HTML helpers. In my view, it seems as one of the biggest offerings of the new version.

  • In ASP.NET MVC 5 we used HtmlHelpers within a Razor View.If we want display Link then we need to create as like below

@Html.ActionLink(“Home”, “Index”, “Home”)

  • In ASP.NET MVC 6, we using TagHelper which is showing below for creating link. It’s become very simple to developers.

<a controller=”Home” action=”Index”>Home</a>

From the above code, we found “controller”,”action” attributes are present in the anchor tag. Here we have big question that is “How do these attributes get mapped to a TagHelper?” So answer is the tag attribute is mapped directly to a C# property and automatically injected.

Let we discuss more details in up-coming posts.

View Components:

In ASP.NET MVC 6, view components has been introduced which is similar to partial views, but they are much more powerful. the one main Limitation of partial view is that they doesn’t have a controller for them. So partial view has little hard to have more complex logic associated with the view. The view component consist of a view and a backing class but it is not a controller.

Let we discuss more details on this topic in up-coming posts.

AngularJS

We aware that AngularJS is one of the popular client-side frameworks for building Single Page Applications (SPAs). VS 2015 includes templates for creating AngularJS modules, controllers, directives, and factories.

ASP.NET Dependency Injection Framework

ASP.NET 5 has built-in support for Dependency Injection and the Service Locator pattern. So we no need to depend on third-party Dependency Injection frameworks such Ninject etc.,.

Cloud Optimization

ASP.NET MVC 6 is cloud optimized applications. During the run time it automatically applied the correct version of the library when our MVC application is deployed to the cloud. The ASP.NET MVC 6 framework is designed for the cloud optimized . The main advantage of having a cloud optimized framework is we can have different versions of the CLR reside side by side for different websites running in the cloud.

Ajax Helpers in ASP.NET MVC

Ajax Helpers:

We already aware that we use HTML helpers to create a forms with the user’s controls. ASP.NET MVC provides another option that is Ajax helpers functionality to our web applications. The main purpose of AJAX Helpers are used to create AJAX enabled forms and links which performs request asynchronously.

When to use?

Here big question will raise, both HTML helper and AJAX helper method generate the anchor tag then why we need to use the @AJAX.ActionLink instead of @HTML.ActionLink ? The solution will be,

  • When the user clicks on the link and it want to redirect to another page then we can use @HTML.ActionLink.
  • When the user clicks on the link and don’t want to redirect to different page, need to stay on the same page (without Post Back), then we can go for @AJAX.ActionLink.

Difference between Html and Ajax helper:

  • HTML helper class performs request synchronously.
  • Ajax helper class performs request asynchronously.

Namespace: System.Web.Mvc

Unobtrusive AJAX

ASP.NET MVC supports unobtrusive Ajax which is based on jQuery. The unobtrusive Ajax is used to define the Ajax features through in our application. While creating project in ASP.NET MVC, the jquery-unobtrusive-ajax.js and jquery-unobtrusive-ajax.min.js files has added automatically to our application as shown below.

Ajax helper Properties and its use :

Property Description
Url Specify the URL that will be requested from the server.
Confirm Given message will be displayed in a confirm dialog to the end user.The ajax call will trigger after clicked OK button
OnBegin The javaScript function name in OnBegin will be intiated at the BEGINNING of the Ajax request.
OnComplete The javaScript function name in OnComplete will be intiated at the END of the Ajax request.
OnSuccess The javaScript function name in OnSuccess will be intiated when Ajax request succeed.
OnFailure The javaScript function name in OnFailure will be intiated when Ajax request failed
UpdateTargetId Specify the target container’s Id that will be populated with the HTML returned by the action method.
InsertionMode Specify the way of populating the target container. The possible values are InsertAfter, InsertBefore and Replace (which is the default).
LoadingElementId Specify progress message container’s Id to display a progress message to the end user while processing the Ajax request.
LoadingElementDuration Specify a time duration for controls the duration of the progress message during the Ajax request.

Example 1 : With Simple Ajax call

Below example code shows how to use AJAX action link in Asp.Net MVC.

@Ajax.ActionLink("Get User Details", "GetDetails", new AjaxOptions
{
UpdateTargetId = "divGetAllUsers",
HttpMethod = "GET",
OnSuccess = "fnSuccess",
})

OUTPUT:

Run the application and  we can see that the he ajax helper Action link has converted to the HTML anchor link element as shown below.

<a data-ajax=”true” data-ajax-method=”GET” data-ajax-mode=”replace” data-ajax-success=”fnSuccess” data-ajax-update=”#divGetAllUsers” href=”/Ajaxhelpers/GetDetails”>Get User Details</a>

Example 2 : With “Confirm” properties

View:

<h2>Index</h2>
@Ajax.ActionLink("Get User Details", "GetDetails", new AjaxOptions
{
UpdateTargetId = "divGetAllUsers",
Confirm = "Aru u sure want to Get all the USER DETAILS",
HttpMethod = "GET",
OnSuccess = "fnSuccess",
})


OUTPUT:

Run the application and click the “Get User Details”, then it will show the pop up for confirmation to proceed. If u click “Ok” then it will process the Ajax request. If we click “cancel” then it wont process the Ajax request.

Note:

The following things need to be required before using ajax helper class.

Required reference:

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

Required Configuration:

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

ActionVerbs Attributes in Asp.Net MVC

ActionVerbs are used when we want to control the selection of an action method based on a Http request method. For example, if we have two action method with same name then it can be respond based upon the HTTP request type(one action has  to respond to Http Get and another method have respond to Http Post). ASP.NET MVC provides attributes to tweak how the actions can be selected based on the name.

Different types of ActionVerbs

ASP.NET MVC supports different types of ActionVerbs.

  • HttpVerbs.Get – retrieve the details from the server. Parameters will be appended in the query string.
  • HttpVerbs.Post – submit new details.
  • HttpVerbs.Put – Use to update an existing information.
  • HttpVerbs.Delete – To delete an existing information.
  • HttpVerbs.Head – Identical to GET except that server do not return message body
  • HttpVerbs.Patch – Requests that a set of changes described in the request entity be applied to the resource identified by the Request
  • HttpVerbs.Options – Represents a request for information about the communication options available on the request/response identified by the Request

In ASP .NET MVC, it can be achieve in two different ways.

Method 1: AcceptVerbs Attribute

We can apply multiple http verbs using AcceptVerbs attribute by using OR operator.

public class dotnethelpersController : Controller
{
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult EditEmpDetails(int id)
{
// retrieve the Details
}

Method 2: shortcut attributes

public class dotnethelpersController : Controller
{
[HttpGet]
public ActionResult EditEmpDetails(int id)
{
}

[HttpPost]
public ActionResult EditEmpDetails(string empCode)
{
}

Points to Remember :

  • If we declare the ActionVerbs then the action methods are selected based on the request methods.
  • Using AcceptVerbs attribute, we can use multiple action verbs in a single action method
  • Multiple action methods can have same name by declaring with different action verbs.

Running Web Application in Multiple Browser Simultaneously

As a web Developer we need to perform cross browser testing in different browser from Visual Studio. In common, we will run the application(pressing F5) after selecting the specific browser from the menu. To test more than one browser simultaneously, VS have an option to set “multiple browser” option. Let we discuss, how to enable multiple browser as a default browser in visual studio.

Why it’s needed?

It is difficult for the developer who working on the browser compatibility because they need to run the solution for every time with different browser. To overcome, in VS has a specific feature that will run the application in many browsers at simultaneously. This feature will be a productivity enhancer for web developers who all working on the browser compatibility.

Step:1

As below image, click the run to show the list of browsers as shown below. As default, we will able to see all added browser and with default browser as checked

Step:2

Click on the “Browse With” option to open a new wizard as shown below. From this screen, we can choose a browser that needs run simultaneously for our application. Select required browsers by pressing the control key (for multiple selection) and click “Set as Default” button.

Step: 3

Now we can see the “Multiple Browsers” item present as default in the menu. Now run the application without debugging(Ctrl+F5) mode to launch in all browser at the same time.

Note :

If we run the application in the debugging mode (F5) then it will show popup for choosing the single browser.

Happy Codding !!!

ValidateInput Attribute in ASP.NET MVC

In some scenario, we need to send HTML value/content as input to our application from the view to the controller. In some time we use HTML Editors to save the HTML content if the end user accept. By default, ASP.NET MVC framework prevents you from submitting the HTML content/potentially malicious content to the controller, for avoiding the cross site scripting attack. This feature is called request validation.

Used Version Detail : Visual studio 2013, Version 4.5, MVC 5

Controller:

This is the simple ValideInput controller and it will render the view as output. And in the form submission, it will redirect to GetDescription() action and bind the view. In default, ValidateInput attribute parameter is true (ValidateInput(true)).

public ActionResult ValideInput()
{
return View();
}
public ActionResult GetDescription(FormCollection _inputDescription)
{
 //your logic
 return View();
}

View:

Here it is the view for getting the form data from the user, which contain one textbox and submit button inside the BeginForm. After user submission it will redirect to the GetDescription action method inside the dotnethelpers controller.

<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@{
using (Html.BeginForm("GetDescription", "dotnethelpers"))
{
<input type="txtDescription" name="description" /> <br />
<input type="submit" value="Submit Form" />
}
}
</div>
</body>
</html>

Output :

As per below screen, we are entering a content with HTML elements. And once we click on the submit button, then it will throw the error as like below because, in default ASP.NET MVC prevents the HTML element as form data. In simple, ASP.NET MVC cannot send HTML values to the controller.

Note:

This is not an issue, it is default security validation handling by the ASP.NET MVC. In some scenario we need to override this  security by using the ValidateInput attribute to prevent HTML explicitly.

Implementing ValidateInput attribute:

In default, ValidateInput parameter is true (ValidateInput(true).

[ValidateInput(false)] public ActionResult GetDescription(FormCollection _inputDescription) { return View(); }

GetDescription View:

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GetDescription</title>
</head>
<body>
<div> 
<h1>GetDescription View : Making validation using ValidateInput(false) attribute</h1>
</div>
</body>
</html>

Run the application and apply the Html element as input (Ex : http://localhost:62536/dotnethelpers/ValideInput).
Now its redirect to the “GetDescription View” instead of throwing the potential error as shown below.

 

Make Note Before Use:

  • XSS (Cross site scripting) is a security attack where this can inject malicious code while input the entry.
  • In ASP.NET MVC, it prevented the above attract by default.
  • ValidateInput attribute is unsafe because it still allows others to inject malicious code.
  • It can be applied on the controller/action level, but not for model property.
  • Model level can be handle by using [AllowHtml] attribute
  • public class UserDetails
    {
    [AllowHtml]
    public string userDescription { get; set; }
    }

 

Happy codding !!!