Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

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....

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...

Wednesday, March 5, 2014

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....


Monday, January 27, 2014

How to pass parameters to Kendo UI control through a data method instead of reading it through read action


Lets review a new way to pass parameter to Kendo Dropdownlist. This option is straightforward, when you have a parameter to invoke and nothing else to be processed while doing this.


Below is a sample code which will load a Kendo DropDownList with a defined parameter.



       The above can be achieved as below too.  Both the methods do the same thing, except in the method below, we can demand to do some extra steps and retrieve value to be passed. This might come in handy, when you want to read a control, which will not be loaded with data, while loading this control. There are few other instances, where this will be helpful. Once you have the parameter, you just have to invoke a force read for this drop down and the results will show up.

The sample code to do the same is given below....


Friday, January 17, 2014

To call a controller method in MVC from UI with callback to read callback data..

In this example lets review the code to invoke a controller method from UI and get JsonResult back. Based on the output data, we can loop through the records to retrieve the values.

Lets start writing the script to invoke it from View.....


In the above, Url.Action method, first parameter is the method to be invoked within HomeController, which is GetDatafromControllertoDisplay and the next one is the controller name. If any parameter needs to be passed, then pass it as above indicated (as it is done for param1).

Below is the callback method that will return data from the controller.


If multiple rows returned, use foreach statement, to loop through the records.



Saturday, January 11, 2014

Calling a Controller method from UI

In this post, I will talk about accessing a method in Controller and displaying the returned data inside a div tag.

I am displaying a scenario here, where I would like to retrieve logged in user id from a controller method and to display the same within the div tag.

In my sampleview.cshtml

Logged in user : <div id="username"></div>
Below is the ajax code, that will invoke a method (GetUserName) from my controller and on successful retrieval, it can be read at the success event. I had used an alert to identify the successful event return for data.

  You can even load this inside a button click event, if you want the data to appear conditionally.

<script>
var url = '@Url.Action("GetUserName","Home")';
        $.ajax({
            url: url,
            type: 'GET',
            success: function (data) {
                alert("data returned");
                $("#username").html(data);
            }
        });
</script>

   In the above case, returned data will be displayed as HTML content within the div tag "username"

Now lets take a closer look at the controller method that will return the string to be displayed in view.

Controller:
public class UserName : Controller
{
        public string GetUserName()
       {
             // Data access code goes here...
             return stringvalue;
        }
}

  I was debugging a code similar to the above for drop down change event and discovered that my calls are working only for the first time and it did not hit my debugger inside GetUserName for the rest of my attempts. Though it was confusing initially, it took a while, before I realized that I was missing cache specific statement, which defines if the call needs to be made every time it is invoked or to re-use cached data.

 Below is the final script, that can be used to invoke for every change/click event.

<script>
var url = '@Url.Action("GetUserName","Home")';
        $.ajax({
            url: url,
            type: 'GET',
            cache : false,
            success: function (data) {
                alert("data returned");
                $("#divid1").html(data);
            }
        });

</script>