Search in Help for developer site.

Sunday, 21 May 2017

How to overcome difficulties facing in jquery ajax call and handling it to get proper response from ASP NET MVC Action Method

Difficulties facing in  jquery  Ajax call and handling it to get proper response from server side code(MVC)


1. Overview

Most of the time you may face some challenges during jquery  ajax call ,say.. you may not get expected response from server side code, showing some internal server 500,or uncaught error right?.. So.. yes, today I am going to explain you guys how to overcome this kind of rigid situation.

Assuming that you already have a MVC application. And below line of code indicates jquery Ajax call to post employee data to server and user should expect employee data for searched parameters and obviously bind them to the model ,display on the UI. So let's begin..


function SearchEmployees() {
var empName = $('#Name :selected').val();
var JoinedOn= $("#JoinedOn").val();var url = '@Url.Action("SearchEmployees", "Home")?empName =' + empName + "&&JoinedOn=" + JoinedOn
$.ajax({
url: url,
type: 'POST',

dataType = "json";
contentType = "application/json";
success: function (result) {
$("#divEmployeeSearch").html('');
$("#divEmployeeSearch").html(result);
}
});


----------------------------------------------
 
[HttpPost]
public ActionResult SearchEmployees(string
empName , DateTime JoinedOn)
{
EmployeeData objEmployeeData = new
EmployeeData ();
BOEmployeeData  objBOEmpl = new BOEmployeeData ();
objEmployeeData .lstEmployees= objBOEmpl .SearchEmpRecords(empName , JoinedOn);
return PartialView("_EmployeesRecordSearch",
objEmployeeData);
}
 


So, in above code you can observe that we are searching employees through Ajax call by passing required parameters to the action method which in turn returns employees list data which matches the passed parameters.

Ok now if you run the application and  pass the parameters to the server, you should expect employees results on your screen right? But I say obviously you will not. Because as we have written bad line of code ,so we wont get employee data on UI.
Lets find and figure out the code which causing the error.


In  Ajax call we mentioned like ,
dataType = "json";
contentType = "application/json";


So,it clearly indicates that we are expecting result in Json data type..but what we are actually returning?did you observe?..

return PartialView("_EmployeesRecordSearch", objEmployeeData);

In above line you can observe, we are returning PartialView which contains list of employees. So what  we are expecting server to return data is not at all matching what actually server method is returning.

Solution:
So, this may result in uncaught error or some internal server 500 error. To overcome this exception, simply remove below line of code from your Ajax call
.
dataType = "json";
contentType = "application/json";

That's it. It should work :)


Note:

1. In Ajax call name of the parameters which you are sending to server method should match with server method parameters. Say, name and data type.

2.If you design server method in such a way that parameters should accept null values also, you should declare them as null able parameters otherwise Ajax call may fail if you pass null values to the method.


Thank you friends.:)
Please feel free to ask your doubts and questions. I will be glad to help you all. And Hope this article will help you guys.


Saturday, 13 May 2017

How to enable ajax pagination and sorting in asp net mvc webgrid

Enable ajax pagination and sorting in asp net mvc webgrid

1. Overview

We all know how to use WebGrid in ASP.NET MVC but when it comes to paging and sorting in WebGrid all developer goes with the traditional way or they will find Custom Paging, Client Side paging etc and even me also.

One day when i was developing an application where i need to use WebGrid then i found that WebGrid has a great feature for paging and sorting.

when you enable this feature the traditional synchronize paging and sorting shall be converted to asynchronize paging and sorting.

2. Enabling Ajax Paging and Sorting

First create a asp.net mvc project in visual studio and add a view and inside view create a WebGrid like below.

Index View Code:

@model List<SampleApp.Models.Employee>
<h2>Ajax Paging and Sorting in WebGrid </h2>

@using (Html.BeginForm())
{
    <div>
        <span id="loader" style="display:none;"> WebGrid is loading</span>
        <div id="gridDiv">
            @{
                var grid = new WebGrid(Model, rowsPerPage: 5, canPage: true, canSort: true, ajaxUpdateContainerId: "gridDiv");
                @grid.GetHtml();
                //In Get Html method you can customize your columns
            }
        </div>
    </div>
<script>
    $(document).ready(function () {
        $(document).ajaxStart(function () {
            $("#loader").show();
        }).ajaxStop(function () {
            $("#loader").hide();
        })
    })
</script>
}

As you can see that its a Normal WebGrid with a only difference of highlighted text:
ajaxUpdateContainerId :The value of the Html id attribute that is used to mark Html element that gets dynamic ajax updates that are associated with WebGrid instance.

So now when you click on any pagination link or sorting link then the whole page won't refresh instead of that only webgrid is going to refresh using asynchronous request.

To see the effect i have added ajaxStart and ajaxStop method that will show the loading text when an ajax request starts and hide loading text when it stops.
<script>
    $(document).ready(function () {
        $(document).ajaxStart(function () {
            $("#loader").show();
        }).ajaxStop(function () {
            $("#loader").hide();
        })
    })
</script>


3. Summary

We saw that how we can convert traditional synchronous pagination and sorting to asynchronous paging and sorting.
Using ajaxUpdateContainerId  option .
Do put your comments and queries in the comments section.




Thursday, 11 May 2017

Calculate time taken by an Action Method in ASP NET MVC

Calculate time taken by an Action Method in ASP.NET MVC

What is Action Filter?

An Action Filter consists of logic that runs directly before or directly after an action method runs. You can use action filters for logging, Tracing, authentication, output caching, or other tasks.

Use of time taken by an Action Method

When we know that how much time an Action Method is taking when it completes its execution. The time can be used in many scenarios like Application slowness issue.
We shall be able to identify which Action Method is taking time above an average time and that action method can be tuned.

Lets get started

 Create a new asp.net mvc project in visual studio.

After creating the project there would be a App_Start folder.
All the filters relies in App_Start folder so we will be adding our filter in app_start folder.

Add a new class with the name of ActionTimeFilter and inherit it by ActionFilterAttribute class.

ActionFilterAttribute Class has two methods OnActionExecuting and OnActionExecuted.

OnActionExecuting method executes before an action method is executed and OnActionExecuted method executes after an action method is executed.

So lets override them


using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TimeTakenByActionMethodDemo.App_Start
{
    public class ActionTimeFilter:ActionFilterAttribute
    {
        Stopwatch stopwatch = new Stopwatch();
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            stopwatch.Restart();
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            stopwatch.Stop();
            TimeSpan timeTakenByActionMethod = stopwatch.Elapsed;
            //save this time to database for tunning purpose or any other.
        }
    }

}

As you can see i use Stopwatch to calculate the time so these above methods will executes for every action method that exists in your application.

If you don't want to run this filter on every action method then remove the filter from Global Filters collection and decorate those action method with this filter. So that this filter will only executes for the decorated action method. see the following example.


  [ActionTimeFilter]
        public ActionResult Index()
        {
            return View();

        }
Now only the Index action method shall be traced.

Next step is to register our filter into the Global Filters collection.


   protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //registering filters
            GlobalFilters.Filters.Add(new ActionTimeFilter());

        }

Now Lets put a break point on both methods and run the application to see the elapsed time.

As you can see the elapsed time is 4 seconds and some milliseconds.
Now you can save this Time into the database and you can identify which action method is taking long time to execute.


What do you think?

I hope you found this article useful, do put your comments or any query in the comments section.Thank you!!!