Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. 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....



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

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

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.



Tuesday, January 14, 2014

How to use jQuery within @foreach inside Razor view


In this topic, lets review how to use jQuery in a Razor view within a foreach to loop through model data items and handle their properties.

To achieve that, our first line will be to implement the model that will contain data to be displayed.

    @model IEnumerable<DemoNamespace.Models.TestData>


Once we have the model defined, we can loop through the model and use jQuery to enable / disable a property. This will be handy, when you have dynamically generated id values based on EmpID.

      @if(Model != null)
      {
            foreach (DemoNamespace.Models.TestData items in Model.ToList())
                {
                    @:$('#' + items.EmpID).prop("disabled", false);
                }
        }


Happy coding....

Kendo UI - Select event (Kendo Drop Down List)


In a Kendo UI development, it provides developers with more flexible options and easier approach towards our development needs. Whenever there is a need to trigger an ajax call or set another value within the form or to do any thing dynamic, select event will provide few ways to achieve this. I had implemented this in a regular usage as well as for dynamically generated controls and it comes real handy in those situations.

  Lets see some ways to handle select events for Kendo UI drop down list.

In this code below, I am trying to initialize a drop down list by providing text field, value field and an option label. When it comes to invoking methods, you can define as many as you might need within the Events option.

  Here this example will deal with select event only. This code, invokes SelectionUpdate method on change of a drop down, where we can retrieve data, either through event argument or through jQuery.


In this code snippet below, the same selection change event can be accomplished just by writing your function within the @<text> </text> tags.


Either way, the code gets executed, but depends on individuals comfort level.  Having it within a script tag, will help to gather all the scripts together in a separate file and might help towards easy maintenance.

Monday, January 13, 2014

Few simple and effective usages for jQuery......

jQuery is a powerful tool that can enhance our capabilities to deal with data in a better way. Following are few ways to effectively use jQuery within a given application ( I had used it mostly with MVC style of applications).


To update a value within a span tag.

<span id="testspan"></span>
<script>
$("#testspan").text("updating span tag value");
</script>

When you run the app, span tag will be updated with the new value.

To enable and disable a field in UI using jQuery

<input type="text" id="txtField"/>
  • To disable, just use -  $("#txtField").attr("disabled", "disabled");
  • To enable, $("#txtField").removeAttr("disabled");

To hide and display a field

<input type="text" id="txtField"/>
  • To hide, just use $("#txtField").hide()
  • To display, use $("#txtField").show()
  • To add animation while displaying, try $("#txtField").show("slow")

To check if an element is enabled or disabled

<input type="text" id="sample"/>

jQuery to check enabled / disabled status...

if($('#sample').is(':disabled') == false)
{
    alert("text box is not disabled...");
}

Above line of code will check if it is enabled and if so will given an alert.

To disable a given element

<input type="text" id="sample"/>

$('#sample').prop('disabled', true);

To disable a given element and its children

<div id="divtest">
  <input type="text" value="test" id="text1"/>
   <input type="button" id = "btnTest"/>
</div>

$('#divtest').children().prop('disabled', true);

Above line of code will disable all elements that exists within the div tag.

To check if an element exists

if ($('#dividtest').length > 0)
{
    //element exists
}
else
{
    // no such element exists.
}

To enable a Kendo UI drop down list

A simple usage to enable (or even disable) a given Kendo UI drop down.

$('#kendoddl').data("kendoDropDownList").enable(true);

Similarly, other kendo UI controls can be handled too.

To modify height of a div tag at run time

A very easy and simple way to do this using jQuery is :

<div id="1"></div>
<script>
$("#1").css('height', '400px');
</script>

To know if an element is visible

<div id="1"></div>

<script>
$("#1").is(':visible');
</script>

Sunday, January 12, 2014

Kendo UI drop down - How to force a second drop down to read data source after first drop downs selection event without using Cascading

In this case, lets review the scenario first. I have  a drop down ddl1, on its selection event, I would like to read data source for second drop down ddl2.

In the code below, I will create both the drop downs and give a data source to read initially. For my second drop down, I will pass an empty string to avoid loading data.

Below is the code to define my drop down lists:

  In the first one, I had defined text and value fields along with my controller method, similar to ddl2. But for ddl1, I do not require any input parameters. So when loading the UI, ddl1 will be loaded and I will disable the second one, until it is ready to read and load data.

@(Html.Kendo().DropDownList()
                    .Name("ddl1")
                    .OptionLabel("Select an option for ddl1....")
                    .DataTextField("textvalue") // value to be displayed in the drop down
                    .DataValueField("idvalue")
                    .DataSource(source =>
                    {
                        source.Read(read =>
                        {
                            read.Action("Getddl1Data", "DataLoad");
                        });
                   })
                  .Events(events => {events.Change("Loadddl2");    })
                    )

Script below will disable ddl2 until, I will force it to read.

<script>
var ddlltodisable = $("#ddl2").data("kendoDropDownList");
ddlltodisable.enable(false);
</script>

In my second drop down list, I am passing an empty string to avoid data being read and load for the first time.

@(Html.Kendo().DropDownList()
                    .Name("ddl2")
                    .OptionLabel("Select an option for ddl2....")
                    .DataTextField("textvalue")
                    .DataValueField("idvalue")
                    .DataSource(source =>
                    {
                        source.Read(read =>
                        {
                            read.Action("Getddl2Data", "DataLoad", new { parameter1= "" });
                        });
                   })
 )

Below is the script to enable ddl2 and read data with a parameter value from ddl1.

function Loadddl2() {
        $("#ddl2").data("kendoDropDownList").enable(true); //enable drop down list 2
     
        // force read data source for drop down list 2
        var readddl2= $('#ddl2').data("kendoDropDownList");
        readddl2.dataSource.read({ paramvalue: $('#ddl1').data("kendoDropDownList").value() });        
   }


Lets review the controller methods here...

public class DataLoadController : Controller
{
   
      public JsonResult Getddl1Data()
      {
   
             return someobjectforddl1;
       }

       public JsonResult Getddl2Data(string dropdownvalue)
     {
           if(!(string.IsNullorEmpty(dropdownvalue)))
          {
                     // run the code to retrieve data only when valid input
                     return someobjectforddl2;
           }
      }

}

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>