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="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></' + 'script>');
    }

</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 :

<script>
   localStorage.setItem("firsttest", "Hello user...");
</script>

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

<script>
  var testvalue =  localStorage.getItem("firsttest");
</script>

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.

jQuery.support.cors = true;

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

The final result is below:


Happy coding...