All posts by Thiyagu

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.

OptionsDescription
acceptsThe content type sent in the request header that tells the server what kind of response it will accept in return.
asyncBy default, all requests are sent asynchronously. Set it false to make it synchronous.
beforeSendA callback function to be executed before Ajax request is sent.
cacheA boolean indicating browser cache. Default is true.
completeA callback function to be executed when request finishes.
contentTypeA string containing a type of content when sending MIME content to the server.
dataA data to be sent to the server. It can be JSON object, string or array.
dataTypeType of data that we receiving back from the server.
errorA callback function to be executed when the request fails.
headersAn object of additional header key/value pairs to send along with request.
isLocalAllow the current environment to be recognized as local.
statusCodeA JSON object containing numeric HTTP codes and functions to be called when the response has the corresponding code.
successA callback function to be executed when Ajax request succeeds.
timeoutA number value in milliseconds for the request timeout.
typeA type of http request for operation e.g. POST, PUT and GET. Default is GET.
urlA 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 NameShorthand 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 :

PropertyDescription
UrlSpecify the URL that will be requested from the server.
ConfirmGiven message will be displayed in a confirm dialog to the end user.The ajax call will trigger after clicked OK button
OnBeginThe javaScript function name in OnBegin will be intiated at the BEGINNING of the Ajax request.
OnCompleteThe javaScript function name in OnComplete will be intiated at the END of the Ajax request.
OnSuccessThe javaScript function name in OnSuccess will be intiated when Ajax request succeed.
OnFailureThe javaScript function name in OnFailure will be intiated when Ajax request failed
UpdateTargetIdSpecify the target container’s Id that will be populated with the HTML returned by the action method.
InsertionModeSpecify the way of populating the target container. The possible values are InsertAfter, InsertBefore and Replace (which is the default).
LoadingElementIdSpecify progress message container’s Id to display a progress message to the end user while processing the Ajax request.
LoadingElementDurationSpecify 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 !!!

Error Handling in ASP.Net MVC Using HandleError Attribute

Exception handling plays an important role in any application, whether it is a web application or a Windows Forms application.Implementing a proper exception handling in our application is important. In most scenario, after we caughtthe exception, we have to log the exception details or show a friendly message to the user. ASP.NET MVC provides built-in features for exception handling through exception filters. The HandleError is the default built-in exception filter which is used to handle the exception. In this post, we are going to discuss about the HandleError filter.

What HandleError filter do?

ASP.Net MVC HandleError attribute provides a built-in exception filter. The HandleError attribute in ASP.NET MVC can be applied over the action method as well as a controller or at the global level for handle the exception in controller and action level. While creating our application, the HandleError attribute is automatically included within the Global.asax.cs and registered in FilterConfig.cs as shown below.

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

It can applied at the global level as well. The HandleError attribute is the default implementation of IExceptionFilter. The HandleError filter handles the exceptions which been raised at the controller/actions. Then it return a custom error view. Let we discuss detail about with example.

Limitation of HandleError Filter:

  • It catch only 500 Http error and not catch HTTP errors like 404,401 ..
  • It has no support to log the exceptions. We can log the exception by create custom error filter by implementing HandleError class.
  • It doesn’t catch the errors that occur outside the controllers and also not catch the ajax calls error too.

Properties in HandleError Attribute

The HandleError Error attribute has a few properties for handling the exception.

ExceptionType: It is used to specify the type of exception to be catch. If this property is not set then it will handles all type exceptions.

TypeId: Set the unique identifier for this attribute

View: Need to specify the name of view. It will redirect to particular view when exception occur.

Master: Master View for displaying the exception.

Example:

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

While creating ASP.NET MVC application the error.cshtml view is created automatically under the shared folder. Creating our own CustomError.cshtml view for displaying error with custom content for the user.

Controller:

HandleErrorAttribute controller has an index action method. From the below code, When the NullReferenceException error happens in the action Index, then the ASP.NET MVC HandleError attribute will find in a view called “CustomError”, in the shared folder and renders it to the user. (Placing in the “Shared” Folder, will be shared with all controllers).

public class HandleErrorAttributeController : Controller
{
[HandleError(View = "CustomError")]
public ActionResult Index()
{
throw new NullReferenceException();
}
}

Sample Attribute :

  1. [HandleError(ExceptionType = typeof(System.Data.DataException), View = “DatabaseError”)]
  2. [HandleError(ExceptionType = typeof(NullReferenceException), View = “NullReferenceError”)]

Web.config

The HandleError filter works only if the <customErrors> section is turned on in web.config.

<system.web>
<customErrors mode="On"></customErrors>
</system.web>

Output :

Note:

  • The HandleError filter works only if the <customErrors> section is turned on in web.config.
  • We can use HandleError Attribute for the entire application by registering it as a global error handler.

 

LowercaseRoutes – ASP.NET MVC routes to lowercase URLs

About this Article

We aware of that our Asp .Net MVC application generate mixed-case URLs like https://dotnet-helpers.com/Home/About or https://dotnet-helpers.com/home/about. So if we type URLs then it wont consider the upper case or lower case. In ASP.NET MVC, route generates outgoing URLs based on the casing of our controller and action names. By default, ASP.NET MVC controllers are classes and actions are methods,so these outgoing URLs are likely be camel-case.

Having Two URLs make problem in Search Rankings:

In ASP.NET MVC, the URLs generated by the routing mechanism are based on the controller and action names. Technically be considered , this will lead to duplicate pages with the same content. Most SEOs will recommend sticking to have only one version.

Solution :

LowercaseUrls property on the RouteCollection class has introduced in ASP .NET 4.5. Using this property we can lowercase all of our URLs.

Eg : routes.LowercaseUrls = true;

Example :

RouteConfig.cs

Include below pieace of code in the RouteConfig.cs file to convert all the URLs in to lowercase.

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.LowercaseUrls = true;

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

Controller:

A simple controller which has two action method namely LowerCaseUrls and LoadUserDetails.

public class dotnethelpersController : Controller
{
   public ActionResult LowerCaseUrls()
   {
      return View();
   }
   public ActionResult LoadUserDetails()
   {
       return View();
   }
}

LowerCaseUrls.cshtml :

<!DOCTYPE html>
<html>
<head>
<title>LowerCaseUrls</title>
</head>
<body>
<div>
      @Html.ActionLink("Home", "LoadUserDetails", "Dotnethelpers")
</div>
</body>
</html>

Output:

After clicking the HOME Link it redirecting to the dotnethelpers/loaduserdetails instead of Dotnethelpers/LoadUserDetails

 

Keep Happy Coding !!!

 

Donut Hole Caching in ASP.NET MVC

Donut Hole Caching is the inverse of Donut cache. As the previous statement, the Donut Caching is used to cache a maximum portion of the view/page, but Donut Hole Caching is used to cache only small portion of the view/page. More about Donut Caching refer here . Donut Hole caching procure by OutputCache and ChildActionOnly attribute.

What is in Mind?

Q1 : What is different type of caching in MVC
We can use OutputCache, DonutCache and Donut Hole Cache to cache the content.

Q2 : When can we implement?
OutputCache – Use when need to cache Whole page/View
DonutCache – Use to cache Whole page expect small portion of it.
Donut Hole Cache – Need to cache small portion instead of caching whole page

When to use ?

Let consider the scenario, having a website which contains the home page with dynamic content(maximum of the page) which load the content based on the user login. And also it has News feed section which contain small portion of the page(static content for all user).

In this scenario, we need to cache the common portion of the page for all the users. So here we cache News feed section instead of dynamic content.

How to Implement ?

In ASP.NET MVC, we can cache whole action with OutputCache Attribute. In mean while if we do not want to cache the entire action, we just want to cache the small portion of page/view. Then this can be achieved by using combination of ChildActionExtensions and OutputCache Attribute.

Controller:

From the below code, the LoadNewsFeed content (ie., loading partial view) in the Index view has cached for 60 seconds for all users expect static content which is specified inside the view.The ChildActionOnly attribute ensures that an action method can be called only as a child method from within a view. In simple, ChildActionOnly attribute are treated as non-action method (It treated as normal method). More about ChildActionOnly

public class DonutCacheController : Controller
{
public ActionResult Index()
{
ViewBag.CurrentDataTimeMessage = DateTime.Now.ToString();
return View();
}
[ChildActionOnly] [OutputCache(Duration = 60)] public ActionResult LoadNewsFeed() { ViewBag.CurrentDataTimeMessage = DateTime.Now.ToString(); return View(); } }

View

Creating a view with displaying current time and render LoadNewsFeed partial view in it.

<h2>Index</h2>
<h3>Message from DonutCache -> Index </h3>
<h3>@ViewBag.CurrentDataTimeMessage</h3>
@Html.Action("LoadNewsFeed")

Output:

Run the application, when we browse DonutCache controller then it will load the index view. If we refresh the page before 60 seconds, then the index view will refresh because it has not cached . But LoadNewsFeed has not refreshed every time because it has been cached by using Donut Hole caching.

 

Keep Happy coding…