Thursday, May 8, 2014

Displaying Wait icon when invoking ajax call...

    In this tutorial, I will go over how to invoke wait icon to display when loading those initial data.. All we need is to define some div tag to show up when it is busy and on the successful return of ajax call, will request the div tag to be hidden and invoke the method(s) for next steps.... (I collected this from few other websites, will try to post the link, when I find it back..).

To get started, lets define a div tag and set up everything that we need to happen when the page is busy loading required data.... Below is a sample of the div tag I am using...

Once we have defined the div tag that will help us display the wait icon, all we need to do is, define where and how it needs to appear. In my code below, I had used before my ajax call and hiding it once I have the successful callback from server. This can be adjusted to suit the needs and handle properly when error condition happens. Code below shows everything that will be needed to display and hide the div tag. 

Happy coding....

Ajax call failed with Internal Server Error (500)

              Recently, when I tried to make an ajax call to my controller, I started getting this error and no way it was visible to me what went wrong. Syntax wise, everything looked great. Passing in the right parameter name from view and it receiving parameter name matched. But this kept occuring only to my last parameter.

               Started looking/searching for possible issues.  It can range between any kind of issues from the size involved for data transfer to missing parameter to setting the data type as string and many more could be found... None of them worked well for me and I know it was a simple mistake that is causing it.

            A quick look again, provided me with what was missing... I am passing in a string value, but receiving as type int. Once I made the type compatible between view and controller, everything started to work.

            Always, this will not be the situation, but this is a possible situation that any one can encounter... Hope this thought / idea will help someone, some where....

 Happy Coding....

Friday, April 4, 2014

Default if Empty...

In this tutorial, will go over using DefaultIfEmpty() in Linq to Objects to handle values when none found.

For this example, I created a sample windows application and wrote the following line of code to test.

In the above code, I had declared a List of type string without adding any values. When I try to access the first value, it is going to throw exception and say none found. Before handling them with try / catch there is another way to add one more step of validation before accessing it.

Above image captures an exception thrown when accessing data in an empty object. In this scenario, there is always an option to use a default value, when no items found. For example, see the image below...

To handle this situation, I had introduced the option to provide Empty string as substitute when list contains no items. Now, when I run the sample code, the output message box will be....

Here, the messagebox displays the default value i.e. empty string. Now lets add some values and try to run the same.

In the above scenario, I added two values to the list item and invoking it will give me the result as User1 (first item in the list). Also, you can use any string value to replace empty string to validate null situations.

Happy coding...

Wednesday, April 2, 2014

Loading jQuery on demand...

There might be situations, where we need to navigate to a new View / Page which does not be part of _layout.cshtml (that is the place where the common includes go). It might help there to check if jQuery is loaded and if not, then it can be included on that page on demand.

An example that worked for me is,

<script type="text/javascript">

    if (typeof jQuery == 'undefined') {
        document.write('<script type="text/javascript" src=""></' + 'script>');


I got this reference from a website (which I don't remember), but there are many interesting flavors to it available on the web....

Happy coding....

Friday, March 28, 2014

Moving data from one view to another view in MVC

Though there are many ways to handle this situation, I recently had to try the same and ended up using localStorage and it really helped to handle data at various levels of requirements.

Getting to use it is so easy and simple. Just make sure you have HTML5 for schema validation and rest is swift.

When setting up the value, this is what needs to be done :

   localStorage.setItem("firsttest", "Hello user...");

When retrieving the value, just do it as below..

  var testvalue =  localStorage.getItem("firsttest");

On a quick note, lets see what is localStorage.

   localStorage - These are nothing but Web Storages, replacing the need to use cookies. Web storages are faster and can accomodate up to 5MB of data. If you want to store / retrieve data based on sessions, then the above can be replaced to use sessionStorage instead of localStorage.

Happy coding....

Wednesday, March 19, 2014

How to implement an autocomplete within MVC

In this tutorial to implement AutoComplete, we will go over a simple way to implement. Before doing so, make sure you have references to jQuery. As a reference, I am giving my jQuery references below (as in _Layout.cshtml)

 In creating the UI, it is a very simple design. More concentration would go on the script that ties up data with the text box. Just for the tutorial, I am creating a view named AutoCompleteTest.cshtml

  In our first step, will create a text box and assign an id value, to be referenced further.


   Now, will concentrate on getting the autocomplete assigned to this text box, by invoking ajax call to a controller method, which in turn would return a type of List<string> with dynamically generated values as data source for our example.

 Below is the script that we will be using to invoke it. Will go one by one on why and how it is used.

 To initiate autocomplete, we would use jQuery to get the id of textbox and invoke its autocomplete method as $("#txtautocomplete").autocomplete();

If we have an array declared, we can still assign that data as a source or we can write a function as above to invoke ajax call (better with MVC approach) and display the data on its successful get.

Here we declare the datatype is json, since our controller will be returning only json data. Parameter to our controller will be sent via the data option.  Everything else, is a regular definition of an ajax call.

Here, I had defined minLength:1, which indicates, as soon as I start typing, I prefer the autocomplete to start working (hitting my controller method to return matching data). Also for open function, I am trying to set the z-index value to be 1000. This is just to be safe and make sure our autocomplete drop down doesn't be hidden when typing values (more possibility that others with greater z-index might overlap).

  Now that we have everything setup in the UI, lets go create a controller method to return data in json format.

I had written this initial code, just to load the view without doing any thing. Now, will write a method to return data based on the parameter passed.

In this method, I am creating a list type of List<string> and load it with data, by looping through and adding it to them.

Once I have the data ready, I would filter it based on the parameter passed, which is searchtext here and return the filtered list as json result set, back to my view.  Now, we have set up everything that is required to implement autocomplete in MVC. When we run and test it, you should see something like this....

Happy coding....

Wednesday, March 12, 2014

HTML 5 tutorial - How to access web service (Web API) from HTML file

In this tutorial, we will go over, how to retrieve data using ajax and display it within our HTML page.

To start with, will create a new ASP.NET empty web application and keep adding files as and when we need to do.

Select New project option from the menu and select the following option :

Once you do that, the solution explorer should be loaded with your empty file structure.

Now lets add a HTML file and call it HTML_API.  The most important task for me to achieve in this HTML will be to invoke a web service using ajax call and display the results within a table structure.

Once the files is created, lets edit the HTML and make necessary changes to make ajax calls. To achieve this, we need to include jQuery within our script tag. This can be achieved in more than one way.

  1. You could either download the file here and include it in your project
  2. You could use any of the CDN's below and refer them online.

 CDN's are nothing but Content Delivery Network. The purpose of CDN is, they host the required files and by referring them, you can still achieve the same output.

Below is a sample of various CDN options (excludes including through physical path).

In our tutorial, I will be using google api's to refer for jQuery. More over, I will be using the same Web API tutorial (which I used for MVC Grid) to display data. 

Below is the ajax code to invoke Web Service from HTML 5 page.

What is being done here is, invoking the web service and on its successful return with data, we are creating a table row and inserting the values within <td> tags. The whole content is finally appended to the table with id "category" and that would complete the getting results displayed within the table tag.

Below is the image for having the table tag as defined above.

Earlier while testing, I had this error occurring and unable to get the data from database. That's when I realized that I needed the following line. = true;

CORS are nothing but, Cross Origin Resource Sharing and mainly used for Cross-domain requests.

The final result is below:

Happy coding...

Friday, March 7, 2014

Path issues when deploying MVC applications

One of the issues that comes up when deploying MVC projects to server is, having a conflict with script path, images path,etc . The path structure that deployment does is, creating project name folder and beneath, there is folders for image,script, etc. Irrespective of how you had included in the project, this is the final structure that needs to be considered.

   To test the same, I deployed my project with the following structure working fine locally.  This image showed up with no issues, but it did not work after deployment.

<img src="../../Img/test1.jpg" />

  All I had to do is, replace the above with the following code and it works. :-)...

<img src="~/Img/test1.jpg" />

   Very simple, isn't it? This works fine locally and after deployment too... I had seen in many websites, where I was advised to use Url.Content, actually there was no need for me to implement it... every thing started working fine. Just in case, if this scenario doesn't work, you can always consider using Url.Content("~/<path for file>") and that might help you. Just a thought...

Happy coding...

Thursday, March 6, 2014

How to invoke a Web API method within a controller.....

ASP.Net Web API is a powerful tool to retrieve data and to serve a broad range of clients. Once created, it can used to access data in mobile applications too.

   Web API's are helpful to create RESTful services and are similar to MVC controllers, but here the class will be derived from APIController when compared to MVC applications where it will be just Controller. This framework is really helpful to build HTTP based services and can very well control the returned data type  to be json or xml.

   If you are developing an application in MVC, it well suites to have Web API, as it is also based on routing concepts.

 Now lets get into the tutorial to see how to invoke a method in Web API....

 In your MVC controller method, make sure you invoke HttpClient to get started. (for HttpClient, if you have any issues, make sure you refer the namesapce : System.Net.Http;)

 We will use HttpClient and define the URI property within client object as below.....  This defines our base url that the web service is located at...

string url = "http://localhost:1001";
 using (HttpClient client = new HttpClient())
     client.BaseAddress = new Uri(url);

In the above, we are using Headers property to define, what kind of data will be handled from server. In the above scenario, we are letting it know that we are dealing json format data. (you can even prefer to use xml format, based on what fits your need well).

Before invoking the method, we should make sure the controller name and method name that we are about to call for data. This defines our path, that we will be using with our client object.

Example : below is our Web API definition...

Given the class name is WebApiTestController, this is how we will use it with our client object.

HttpResponseMessage msg = client.GetAsync("api/WebApiTest/<MethodName>").Result;

Using the above, we can identify if our call was successful by trying the method :
 if(msg.IsSuccessStatusCode), then we had successfully accessed our method  and we can retrieve our data as below...

var mylist = msg.Content.ReadAsAsync<object>().Result;

To have the list converted to a compatible IList<T> object, you can use Result.ToList(); The resultset would be a List object.

  Below is the compiled list for complete code to invoke a web API method....

Happy coding...

Wednesday, March 5, 2014

HTML Web Grid - How to filter the records using a text box.

In this tutorial, we will go over how to filter a web grid based on an input from a text box. Before getting started, I will be using my earlier tutorial on Web Grid. In that tutorial, I used web service to invoke data from Northwind to display category id, name description etc within a grid.

   Now I will use the same data to filter it based on user input. I will add a textbox and a search button on top of the grid, that will drive the data source to the web grid.

This is my existing screen.

Once I add the new UI elements in this view, this is how my new screen will be...

I had moved my grid to a separate partial view to ease the process of reloading data. I created a new view named "gridview.cshtml" and included the code as given below...

In this view, I had defined an attribute as id using htmlAttributes property. I will be referring this id to display the refreshed data after filtering from existing source.... (I am reusing styles for this grid from various other web sites). Once this is defined, we can start working on UI filter elements and button search click event to do the rest.

I will use a div tag to enclose filter search and the partial view for grid. Below is the code to implement them.

In the above code, I will be displaying the grid through @Html.Partial by passing in the partial view name as the parameter.  By isolating the view to be refreshed, it will help us to re-load it many times, without affecting the other parts of UI.

  Remaining part with the UI will be to write the search click event, before we get into the controller part of the code. Lets write the search event by making an ajax call to the controller method with the parameter value and do a filter on it.

In the above code, I am making a call to my controller method TestPage_Filter, which would fetch the data for web grid without filtering it (by doing it this way, you could use the same code while loading the page too avoiding redundant code). Whatever is entered into the text box will be retrieved for filtering and passed in through the data option. Here we are retrieving the search criteria and storing it in a variable called srchitem. Same will be passed on to the controller on click of the button. On successful completion of process,  the returned data is now loaded into the grid through the grid's id, using .html(result).

This being done, we are totally done with the view side of it. In controller, I had done the same steps for loading the initial grid data and storing it in an IEnumerable<CategoryData> variable. Once I have it there, I use linq to objects to filter my data based on the entered text. Below is the code to retrieve my grid list and filter it.

In the above code, txtval is the parameter passed to the controller method. Here I am doing a filter based on CategoryDescription field, similarly you can do the same for other fields too. Or even better, have a drop down selection in UI and get users response to know, based on which field criteria, it is being searched.

Once I have the filtered list, I will loop through my data model object to map it to my grid elements as below.

If you refer the code above, you can see that the view, I am returning is gridview (the one that contains the grid) along with the filtered data. This data will be associated with the grid and re-loaded. Final view after filtering should be like this....

Happy coding......

HTML Dropdown List

This tutorial will illustrate an example of, how HTML Dropdownlist can be used to load data and include an event to trigger and load another drop down based on the values from the first one.

Open a new MVC project and add a view to execute the following code. For tutorial purpose, I had created a new razor view as HtmlDD.cshtml

 Lets create a class that will be used for the selected values for both the drop downs.

Lets include the model that we will be using in this view.  We will be referring the properties declared within the model and associate them to the selected values in both the drop downs.

 In your view, add the following code for drop down.
In the above code, we included two drop downs. First one will be loaded with values, when loading the page. Second one will be empty, until the we select a value from the first drop down.

To load the first drop down, implement the code below (I am using json data and so I chose to handle it this way).

Until now, running this page should get you displaying with two drop downs (assuming you have an empty structure for htmlDDDemo method), with the first one loaded with values needed. Will go over the rest of code to review, how to implement on change event of first drop down, that will trigger the changes (adding items) to second drop down. This is just my scenario, but again, this can be used to display a Web Grid, filtered by the selected drop down value or other desired actions.

In the above javascript method htmlDDDemo, we are passing in paramvalue, which is the selection from the first drop down and I am passing the same to my controller/methodname?parameter=passedinvalue....

On execution of this script, my second drop down will be loaded with filtered data based on the parameter provided.

Happy coding....

Tuesday, March 4, 2014

Creating basic SilverLight application (for beginners with HTML exposure)

In this tutorial, we will go over how to create a sample XAML (silverlight page) and display with some contents within the grid (table in HTML).

  Also we will go over, step by step to see how the tables in HTML is different from Grids in XAML and how they can be compared to get a better understanding. This will help us in getting a smooth transition from HTML to Silverlight. This tutorial just deals with very basic UI creation demo.

Lets get started with Silverlight application.... When you open a new project, make sure you select Silverlight from installed templates and select Silverlight application and click ok.

Once you click ok, in the next window, you can chose to host the silverlight app in a separate ASP.NET website or when you dont check it, it will generate a startup HTML page. Similarly, you get the option to chose an ASP.NET web or ASP.NET MVC project.

This window also provides the capability to chose the version of Silverlight that should be used to run the app. Once you click ok to create the project, you could see the file structure created below.

In our application, we will be working on a basic code to create and display how a grid works and also in comparison with html table tags.

 In html we have seen table created and handled in many ways as we wanted. Will walk through the html table tags first and their output and then we can follow the steps to generate the same in Silverlight.

In the above, I generated a 3 X 3 matrix and its corresponding output. Now lets see how to create the same in Silverlight.

 Lets start with xaml page listed above, when we look at MainPage.xaml, this is how the code looks. Here UserControl is the basic Content displaying control, which can display any UI elements like textbox, textblock etc.

Here Grid is the basic layout whose rows and columns will be bound to UI elements in this example. We will be expanding this grid with more rows and columns and add textblocks (similar to labels in html) to display their locations within the grid / table. Add the following code inside the grid.

Now press F5 to run.... You should see the following output...

This is a very simple and easy way to get started with Silverlight. In the above code, we could see the text for TextBlocks are displayed in two different ways to show this can be done. To make it more exciting, there are many other third party tools like Telerik that works great with Silverlight to create more easy handling controls for data display.

Happy coding... 

Friday, February 21, 2014

Kendo UI - Tab control

In this tutorial, we will discuss about getting records for Kendo Grid and displaying them. Will also see, how to retrieve a specific column value on click of a row event.

I had written a sample Kendo Grid Html, which will display four columns, namely Employee ID, Name, Join Date and Comments

Data definition for this grid resides in DemoNamespace.Models.TestData, which is nothing but defining properties of the above columns. Once defined, make sure your controller method returns JSON data to be bound to the grid....

In the above, while binding the columns, you could define their width and title attributes as shown.

  .Read will invoke the call to Home Controller -> GetTestData method and returns a result set to be tied up with the grid.

   On selection of a row, the code will start executing the method "recordselected" as indicated. Below is the code where it defines the method and gives an alert of the selected Employee Name.

Few changes are required in controller, before we could run and test it. Here is a sample code of, how the  action method should be defined...

While returning the json result set, it should have .ToDataSourceResult(request), else the grid will not be bound with the returned data... Also parameters must contain [DataSourceRequestAttribute] DataSourceRequest request as the first parameter and other parameters should follow....

Happy coding....

Wednesday, February 19, 2014

MVC Web Grid

In this tutorial, we will go over a simple way to get data from controller and display it in the view using Web Grid.

  For this tutorial, we will be using the Web API tutorial to get the data from Web API source.

   Lets create a view first. I had created a new view in Home folder as TestPage.cshtml

Once the page is created, create a class named CategoryData as below...  This is being used in reference to the Web API we developed earlier. 

To retrieve data from Web API, I will request a call from controller to return all data, which I will tie it up with the grid to display....

 Now, we have everything ready except view. To implement view changes, I will use WebGrid  (make sure you have reference to System.Web.Helpers.dll). Below is the sample code for view.

Now, we are all set to run and test our web grid... But before that, if you are using Home Controller and a different view than index, make sure you update the following changes in App_Start\RouteConfig.cs

Everything is set to run the application. Press F5 and you should see the following output...

The styles implemented so far are pretty simple, you could always refer more at many web sites or be creative to have your own version of styles for table, header, rows, etc...

Happy coding...