HTML5 GeoLocation API to Find User Location

by Naveen 9. June 2011 12:07

Some time back I did a project involving Twitter location and posted some notes about use of geo locaton API at this post, Convert IP Address To Location and Address. Now that HTML5 is picking up steam and all the latest browsers are supporting most of HTML5 specification, use of native Geolocation API in HTML5 will be the way to go as long as your users are using a brwosers that support HTML5. There are some caveats that you need to be aware of before you use GeoLocation API in HTML5.

Privacy: HTML5 specification for GeoLocation API clearly states that the A conforming implementation of this specification must provide a mechanism that protects the user's privacy and this mechanism should ensure that no location information is made available through this API without the user's express permission. What this means is that when you try to use this API, your browser will present user interface to user to get permission. Following images show what this UI looks like on different browsers.

IE9
Chrome
FireFox

GeoLcation API Usage

This API is exposed through geolocation property of navigator object. There are three methods supported by geolocation object.

  • getCurrentPosition: As the name suggests, this function is called to current position of your browser or mobile device.
  • watchPosition: As name suggests, this function is used to monitor or watch position change of your device or browser. This method is very helpful for your mobile device application where your position is going to change as you are travelling. In case of browsers, the position is based on IP address assigned to your network. This position may change if you are using broadband card and your provider switches IP address on you. But overall it is very useful method to monitor the position change and then change the display of UI based on new location.
  • clearWatch: This method works together with watchPosition. It is equivalent to clearing of timer in JS. watchPosition spawns a thread and hands you an ID related to that watch thread. By calling clearWatch method, you can clear that thread.

Asynchrnous Calls

Both functions getCurrentPosition and watchPosition are asynchnronous. This means that you have to provide call back functions to these APIs. These APIs take upto 3 arguments but two are optional. For the API to work, you have to provide atlease call back for success. If you do not provide a call back function for success event then the API will throw an error.

Specifying Timeout

When you are dealing with asynchronous calls, it is very important that you have some time out for request. You do not want to end up in a situation where your request is waiting forever. Depending on settings of your device or browser, there is always a default timeout for a HTTP request, but that time out is longer than you really want to wait for. Third parameter for these function is options. You can set three option parameters for each request and one of them is timeout. Following are three options exposed by this object.

  • enableHighAccuracy
  • timeout
  • maximumAge

Example Code

Following javascript code snippet shows how I used geolocation API to get current position of my browser.

function getMyPosition() {
    if (navigator.geolocation) {
        var geoApiOptions = { timeout: 5000, enableHighAccuracy: true };
        var pos = navigator.geolocation.getCurrentPosition
          (getGeoLocationSuccess, getGeoLocationFail, geoApiOptions);
    }
}

function getGeoLocationSuccess(position) {
    $('#latitudeLabel').text(position.coords.latitude);
    $('#longitudeLabel').text(position.coords.longitude);
    $('#altitudeLabel').text(position.coords.altitude);
    $('#accuracyLabel').text(position.coords.accuracy);
    $('#altitudeAccuracyLabel').text(position.coords.altitudeAccuracy);
    $('#headingLabel').text(position.coords.heading);
    $('#speedLabel').text(position.coords.speed);
}

function getGeoLocationFail(positionError) {
    alert(positionError);
}

$(document).ready(function () {
    getMyPosition();
});

Coordinates In Result

As you can see in example, getGeoLocationSuccess function is callback for request success. This function is called with one parameter, position. This objects has following two properties.

  • coords
  • timestamp

coords object contains the properties that identifes the coordinates and other related attributes for position of the device or browser. This objects has following properties.

  • latitude
  • longitude
  • altitude
  • accuracy
  • altitudeAccuracy
  • heading
  • speed

Of these values, latitude, longitude and accuracy will always be returned when call succeeds. Other properties are optional depending on device or browser's implementation.

Once you have position values, you can use those to do some more interesting things in your applications. I will discuss some of these usages in subsequent posts!

 

Views: 1836

Tags:

HTML | Javascript | JQuery | Web

How to implement OWA style new message notifier poup using Silverlight and javascript

by Viper 6. October 2009 14:06
OWA style new message notification popup

Download Demo Projects

This is one of the projects I have been planning to work on for some time. I was looking into building an event notifier in one of my ASP.Net application. I wanted it to be more like Outlook Web Access (OWA) new email notifier pop-up. It is the one that slides up from bottom right corner of your browser when there is a new email in your inbox. I had built it in the past using all javascript solution. Yes, this Microsoft is one of the earliest implementation of so called AJAX applications. I did not want to deal with all the javascript code related to setting up HTTP calls and then dealing with response and rendering the results.

I wanted to leverage Silverlight to do all the heavy lifting. And use light weight javascript implementation on client to do animated sliding and positioning of the popup notifier box. At the end it turned out be quite an elegant solution that worked on major browsers like Internet Explorer, FireFox and Chrome. This article is an attempt to describe How to implement OWA style new email notifier popup using Silverlight and Javascript.

The implementation involved the following technologies and I will describe how each component was implemented

  • ASP.Net web application
  • ASP.Net web service
  • Silverlight application

ASP.Net Web Service

Let's start with discussion of the component that is responsible for communication of data between client and server application. The client requests data from server at certain frequency to check if there are any new messages. So I implemented as simple ASP.Net web service application with few web methods. For this demo I had a simple method with following signature.


[WebMethod]
public string GetGlobalMessages()
{
 List msgs = MockData.GetGlobalMessages();
 return msgs.ToJson();
}

For demo application, I implemented a MockData class that creates a random list of messages and then serializes that collection as JSON and sends it in response. I implemented ToJson as an extension method on List<StatusMessage> object. You will find it in Extension.cs file in ActivityData project.


public static string ToJson(this List<StatusMessage> msgs)
{
 var ser = new DataContractJsonSerializer(msgs.GetType());
 var ms = new MemoryStream();
 ser.WriteObject(ms, msgs);
 var serializedData = System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray());
 return serializedData;
}

You can see there is nothing fancy about this whole implementation to make it work with a Silverlight client. A very simple ASP.Net web service.

Silverlight Application

This is where all the action happens. There are few components of this application, rendering and data access. Lets us first discuss data access. The client application is to talk to server at certain frequency. That means I need some kind of timer going in the application. When this timer ticks at specified interval of time, it send asynchronous request to server to get new messages. I have implemented this whole mechanism in MessageMonitor application. When this class is constructed, it creates an instance of DispatchTimer. You may be asking why DispatchTimer and why not simple Timer application. The problem is that when you are dealing with user interface application, you can only update the controls on the thread on which they were dispatched. Regular timer does not executes on that dispatcher thread. So if you will try to update your user interface on that thread you will get exception complaining about cross threaded access. Here is the code that created DispatcherTimer for my application.


private void CreateMessagePollTimer()
{
 _messagePollTimer = new DispatcherTimer();
 _messagePollTimer.Tick += new EventHandler(MessagePollTimer_Tick);
 _messagePollTimer.Interval = new TimeSpan(0, 0, MessagePollInterval);
}

When the timer ticks it calls MessagePollTimer_Tick method. And that method makes async request to server to get new messages.


void MessagePollTimer_Tick(object sender, EventArgs e)
{
 if (Stopping || MessagePollInProgress) return;
 GetMessages();
}

When async request to server completes, the following method gets called. You can see that now it uses the same JsonSerializer class to de-serialize the response into list of StatusMessage objects. And then it raises event for objects that have subscribed to the event.


void GetGlobalMessagesCompleted(object sender, 
  SiteMessagePanel.ActivityDataServices.GetGlobalMessagesCompletedEventArgs e)
{
if (e.Error != null)
{
 return;
}
 var msgsData = e.Result as String;
 var msgs = msgsData.FromJson();
 System.Diagnostics.Debug.WriteLine(msgs);
 StatusMessageEventArgs args = new StatusMessageEventArgs(msgs);
 OnStatusMessageReceieved(args);
}

Page class that implements user interface for popup, handles this event and renders all the messages.


void Monitor_StatusMessageReceieved(object sender, 
 ByteBlocks.ActivityData.StatusMessageEventArgs arg)
{
 if (arg.Messages.Count == 0)
 {
 msgTextBlock.Text = "No messages received";
 ShowClientPanel(false);
 return;
 }

 msgTextBlock.Text = string.Empty;
 messagesPanel.Children.Clear();
 foreach (var msg in arg.Messages)
 {
  StackPanel sp = new StackPanel();
  TextBlock tb = new TextBlock();
  tb.Text = msg.Title;
  tb.TextWrapping = TextWrapping.Wrap;
  sp.Children.Add(tb);
  messagesPanel.Children.Add(sp);
 }
 ShowClientPanel(true);
}

ASP.Net application and javascript

ASP.Net application acts as a host for the silverlight control that I created to render messages. I have implemented a simple Server Control that hosts it. Then I added that control inside a simple div on the master page. And I have very simple vanilla implementation of the server control. It does not have very complicated implementation. I simply copied the code generated by silverlight wizard for test page into that control


<div id="statusslideup">
<ByteBlocks:StatusPanel runat="server" id="statusPanel" />
</div>

Calling Javascript Method From Silverlight

So far we have implemented two pieces of the application that drive the data and render it. Now comes the fun part. How are we going to trigger the client to show the popup and animate it to come up from bottom. First, it is Silverlight application that is running the timer. So it is the one that has to trigger the client. I implemented some java script code that shows the DIV that hosts silverlight client component. And then small piece of code that implements animation. Silverlight framework provides a very simple mechanism to invoke any Javascript method that is implemented on client side. I implemented a very simple method in silvelight application to call my JS method whenever there are new messages for the user.


private void ShowClientPanel(bool show)
{
 HtmlPage.Window.Invoke("_showStatusPanel", show);
}

It could not be any simpler. And the following Javascript function implements small piece of code that calculates position of popup notifier window based on browser height and height of element containing silverlight control.


setStatusPanelPosition = function() {
 if (_statusdiv) {
 _maxPanelPos = document.body.scrollTop + ($(document).height() - _statusdiv.clientHeight);
 _curPanelPos = $(document).height();
 if (!_isStatusVisible) {
  _sliderInterval = setInterval("_slidePanel()", 5);
 }
 else {
  _statusdiv.style.top = _maxPanelPos + "px";
 }
 _isStatusVisible = true;
 }
}

Demo Project

Attached demo project is a collection of Visual Studio 2010 projects and solution. If you do not have VS2010, you can simply create a new solution and projects in VS2008 and copy the source files in there. You are also going to need to download Silverlight 3 Toolkit because I use theming controls from that toolkit to give some zing to the UI.

I hope this demo project helps you in building cooler implementations of OWA like message and event notifier windows.

 

Views: 15380

Tags: ,

JQuery | ASP.Net | Silverlight | Javascript | JQuery | Silverlight

How to send data from Javascript to Silverlight control to render charts

by Viper 31. July 2009 15:09

Download Demo Project

I have been discussing use of jQuery to send AJAX request to server to get some data every X number of seconds to get server time and calculate some latency numbers. Now it is time to add some color to it. The numbers that I am getting is great and provide some useful information. But having a visual of how these numbers are varying with time will enhance utility of these statistics. So I decided to add some charts to show these latency numbers are varying with time. In this article I am going to show how you can pass the data obtained from server using AJAX request to a Silverlight application hosted on the page. This silverlight application uses charting control from Silverlight toolkit. Lets see how all this fits together to get this to work.

Bridge between Javascript and Silverlight component

In one of earlier posts, How to setup communication between silverlight applications, I discussed how you set this bridge up. The sample project for that article was done using Silverlight 2. The mechanism to set up the communication bridge has not changed in Silverlight 3. So all those concepts still apply for this project as well. The following code snippets shows declaration of a method decorated with ScriptableMember attribute to let silverlight framework know that this methos is to be exposed to javascript. And in constructor of the page, HtmlPage.RegisterScriptableObject method is called to register the class to be exposed to javascript. I do not want to expose all my properties, fields and methods to javascript. So I have not added scriptable attribute on class itself. I want to control what is exposed and what is not.


public MainPage()
{
	InitializeComponent();
	HtmlPage.RegisterScriptableObject("ClockDataClient", this);
	SetupChartDisplay();
}
		
[ScriptableMember]
public void PutNewClockData(string xtx, string data)
{
	AddDataPointToPlot(data);
}

This completes what needed to be done from silverlight application to expose its end points to javascript. Now we are going to see what is done on pages to communicate to silverlight control.

Setting up the page

First thing you need on the page is to include your Silverlight control. On Default.aspx you will find the following declaration of object tag that will host the control.


<object id="clockDisplayPlugin" data="data:application/x-silverlight-2," 
  type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="ClientBin/ClockLatency.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="onLoad" value="onLoadClockDisplay" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="3.0.40624.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none">
  <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="" style="border-style:none"/>
</a>
</object>

All this code was generated by wizard when I added test paste to my project. I added a new param declaration to handle load event. This event is fired when Silverlight control has been loaded. On lets see what all javascript is required to send message to silverlight control.


function onLoadClockDisplay(sender, args) {
 objClockDisplay = sender.getHost();
}

function sendLatencyData(data) {
 if (null != objClockDisplay) {
  objClockDisplay.Content.ClockDataClient.PutNewClockData("", data);
 }
}

As you can see, in load event handler I saved the reference to Silverlight control object. Then from my ajax request code, every time I got the data from server, I call sendLatencyData method. This method calls PutNewClockData method that I exposed from control using ScriptableMember attribute. This call constitutes of four parts.

objClockDisplay.Content.ClockDataClient.PutNewClockData

objClockDisplay is reference to our silverlight plugin. Content is the property on plugin object through which control's methods are exposed. ClockDataClient is the key that was used to register the class as scriptable in our control. PutNewClockData is the name of the method.

Setting up charting control in Silverlight component

I used charting control from Silverlight Toolkit for my project. I decided to use column chart to display latency numbers over time. In silverlight application project, I added the following XAML on MainPage.


<chartingToolkit:Chart Title="Clock Latency" x:Name="latencyChart" BorderThickness="2">
 <chartingToolkit:Chart.Series>
  <chartingToolkit:ColumnSeries Title="Latency" DependentValueBinding="{Binding Latency}" AnimationSequence="Simultaneous" />
 </chartingToolkit:Chart.Series>
</chartingToolkit:Chart>

In codebehind i created a collection to save data sent from javascript and attached the column series to that collection. I only keep last 11 entries in the collection.


void SetupChartDisplay()
{
 ColumnSeries cs = latencyChart.Series[0] as ColumnSeries;
 foreach(var lItem in cs.LegendItems)
 {
  lItem.Visibility = System.Windows.Visibility.Collapsed;
 }

 latencyChart.Width = 500;
 (latencyChart.Series[0] as DataPointSeries).ItemsSource = DynamicCollectionItemsSource;
}

You can see it was pretty simple to set this whole up and get javascript to send data to silverlight control and render the charts using those numbers.

Click to see demo

Feel free to send any comments or suggestions.

 

Views: 10972

Tags:

HTMLParser | JQuery | Silverlight

how to insert new elements on page in reverse order using jQuery

by Viper 28. July 2009 06:35

prepend enries using jquery

I have been extending the current sample clock synchronization application to add some more features to show more capabilities of jQuery. In the last update I added functionality to display latency numbers when service was called every X number of minutes. If you will let the page running for quite some time you will see how quickly the entries get appended to the display. What we really want is that latest entries should be displayed at the top. So basically instead of appending the new entries, we want to prepend the new entry to the last entry added. We are in luck here. jQuery does offer couple of methods here that makes it easy. prepend, prependTo, before, insertBefore methods are your friend here. It turns out that all these methods get mapped to one function behind the scene, insertBefore. Following code snippet from the application shows entries are added in reverse order.


var elLastLatencyEntry;
var elLastMessageEntry;

function displayLatency() {
 var elToAppend = null;
 if (latency == -1) { elToAppend = $("<p>Initializing</p>"); }
 else { elToAppend = $("<p>" + latency + " ms</p>"); }
 if (null == elLastLatencyEntry)
 { elLastLatencyEntry = elToAppend.appendTo(elLatencyDisplay); }
 else { elLastLatencyEntry = elToAppend.prependTo(elLastLatencyEntry); }
}

You can see from the code that I save the last entry that was added in a variable for later use. This avoids over head of finding the latest entry again and again every X number of seconds.

 

Views: 11182

Tags: ,

AJAX | Javascript | JQuery

How to set correct cache control headers for AJAX response

by Viper 22. July 2009 03:43

I have been developing AJAX enabled applications before the term AJAX was coined. I have been doing it for so long that some of things that I do come kind of naturally. And one of the things that I always do is to make sure that response is not cached to ensure that client is never working on stale response even though it sent new request every few seconds. So I have a small piece of code that I pretty much use in all applications that sets some headers.


Response.ContentType = "text/plain";
Response.Expires = -1;
Response.CacheControl = "no-cache";

These are not just the only headers but gives you an idea how cache was being control. I never ran into any trouble with any applications till last week when I was told that our application is filling up Temporary Internet Files folder of the users. This was the first time ever I was reported such issue and actually this was first time I observed this behavior in my applications. So I fired up Fiddler to see whats going on with my requests. I looked at the response headers and saw the following.

First, I was not expecting to see Cache-Control: private. So that was little out of whack. Second, the expiration time was correct because I always set to an hour behind the response time to make sure that it is stale for caching. I have been using the same caching utility routine for so long that I did not suspect that something is wrong there. Then I looked inside Temporary Internet Files folder again and noticed that this was the only request that was being saved in the folder, others were not. So I looked at the implementation and found that the server side implementation for this request was not using my standard utility to set cache headers. Following is the code snippet that I ad in place. Well why i changed the implementation for this particular call is whole different story.


Response.ContentType = "text/plain";
Response.Expires = -1;

Notice that it is missing Cache-control : no-cache header. That explained everything. After I added this header, everything went back to normal. So I decided to do some experiment to observe behavior of setting different headers.

No Cache-control: no-cache header on any call

You will notice that from my earlier post How to serialize multiple AJAX calls in jQuery, I have two AJAX calls being made. And you can see from snapshot above that both are being saved in Temporary Internet File folder.

Cache-control: no-cache header set on one request only

Now you can see that only one request is being saved in the folder and other has disappeared.

Cache-Control:no-cache header set on all requests

Well, there is nothing to show here in Temporary Internet Files folder because nothing is being saved there any more. But here is the snapshot of response headers as seen in Fiddler.

Now you can see that no-cache header and pragma has been set correctly.

Set cache-control header correctly

As more and more applications are using AJAX or Web2.0 style of implementations, if you do not set these cache control headers correctly, you will see that browser cache folders will accumulate lot of entries. It is not that big of a deal as far as application working goes because this temporary cache will not grow beyond specified limits for a particular browser. But it will hurt performance of other internet sites that you visit because their content will not be found in cache and will have to reloaded from server again. Other performance hit you will take is that now browser has to spend an extra CPU cycle to save these entries on the disk.

 

Views: 9282

Tags: , , , , ,

AJAX | ASP.Net | JQuery

How to use jQuery to make AJAX requests in ASP.Net?

by Viper 20. July 2009 15:06

Download Sample Project

For one of my current project, I have been using ASP.Net AJAX to make async request into my ASP.Net to get some time related data. First, I am not a big fan of ASP.Net AJAX implementation. I will not go into debate on why. There are plenty of discussions on this topic. I will just spare myself from it. Second, the application was already using jQuery for other javascript related implementation. I was like, if we are already using jQuery why have an overhead of introducing Ajax tool kit. So I started porting the implementation to use jQuery. Through this series of posts, I will describe how you can use jQuery to make AJAX calls in ASP.Net applications. Well, the client side javascript can be used in any browser. So other than the server side implementation, there is no nothing specific to ASP.Net per se.

The sample project for these articles is a time synchronization service. The idea is that I want to display clock on the client machine that will display server time. Well you can say there is no big deal with that implementation. On page load, get the server time. Save in some client side variable and run one second timer on it. Well, that works for most part. There are situations where clients are behind really slow connections that can cause of lot latency in request and response. So in those cases, by the time your response gets to the client side, the server time that you returned to client is already behind by few seconds. For applications that has users who depend very heavily on this server time, this latency of few seconds can be very critical. In this first post I am not going to go into details of algorithm that I implemented to reduce this latency adjustment over time. This first sample does a very simple task. It sends asynchronous request to server every 10 seconds. The server returns its time and then client uses that to display clock.

Server Side Implementation

I have a class ClockData that has DataContract attribute set on it. You can pretty much figure out that I am planning on converting this service to WCF service and use the framework facilities to serialize and de-serialize data as well. So I am populating this class with three pieces of data (server time, latency and a cookie) and then using DataContractJsonSerializer class to serialize the data into JSON format and sending it to client.


private void SerializeServerClockData(ClockData data, Stream strm)
{
 var spSer =
   new DataContractJsonSerializer(typeof(ClockData));
 spSer.WriteObject(strm, data);
}

void SendResponse()
{
 long ms = (long)(_serverTime - new DateTime(1970, 1, 1)).TotalMilliseconds;
 var clockData = new ClockData()
  {ServerTime = ms.ToString(), Latency = _latency, ResponseKey = Guid.NewGuid().ToString("N")};
 Response.ContentType = "text/plain";
 Response.Expires = -1;
 Response.CacheControl = "no-cache";
 SerializeServerClockData(clockData, Response.OutputStream);
 Response.End();
}

From the code snippet above, you can see how plain and simple server side implementation is for this first sample. This will get little complicated as I get more into the actual algorithm of calculation of latency reduction.

Client Side Implementation

Since we are going to be using jQuery to make Ajax call, so we will need to include reference to jQuery javascript file. For this sample, I am going to show the AJAX request you can send using jQuery. The library has method named .getJSON that you can call to send the request. You can set the URL where request is to be sent, set the parameters that needs to be passed with request and set the callback function that should be called when request completes. It is that simple. Here is the implementation from the sample.


function getServerTime() {
 cTime = firstRequest ? -1 : curTime.getTime();
 $.getJSON(clockServiceUrl, { clientTime: cTime, requestKey: respKey }, gotServerTime);
}

function gotServerTime(data) {
 firstRequest = false;
 latency = data.Latency;
 curTime = new Date(parseInt(data.ServerTime));
 if (!clockTicking) createClockTimer();
 createServiceTimer(defaultServiceTimer);
}

function clockTick() {
 clockTicking = true;
 curTime.setTime(curTime.getTime() + 1000);
 elClockDisplay.text(curTime.toString());
 if (latency == -1)
 { elLatencyDisplay.text(""); }
 else
 {elLatencyDisplay.text(latency + " ms");}
}

$(function() {
 elClockDisplay = $('#clockDisplay');
 elLatencyDisplay = $('#latencyDisplay');
 getServerTime();
});

In subsequent posts I will discuss how you can control the request little bit more instead of using .getJSON to use default settings.

 

Views: 4465

Tags: , ,

.Net | AJAX | ASP.Net | JQuery

How to format GridView or DataGrid Using JQuery

by Viper 14. July 2009 14:12
datagrid using jquery

Download Sample Project

This is based on a question asked by one of my blog readers.

I have 2 datagrids. Each Grid has the same amount of columns and each grid has a select column as the last column on the right added from the "gridview/ edit Columns/ CommandField/ Add" sequence. The first GridView has the Select column as a Link The second GridView has the select Column as a button I want to be able to change the text for both the Link and button in cell(4), setting them to the value in cell(1) from the same row using the GridView_RowDataBound event. However, using "cell(4).text = cell(1).text" just overwrites the text value removing the hyperlink and button.

The behavior described in this question is as expected. When you set text of a cell in grid, it directly affects HTML that is going to be rendered. When you set text value of a cell, it means that you are setting innerText of the cell. The column that GridView creates for command fields (Edit, Delete and Select) are a (anchor) or button elements. So you can see what will happen if you set text value in that cell. It will wipe out those link or button controls and replace them with simple text string.

There are properties like EditText, DeleteText and SelectText for CommandField column in grid view. If you try to set these values using a server side method by passing it DataContainer object, you will get following exception thrown.


Databinding expressions are only supported on objects that have a DataBinding event. 
System.Web.UI.WebControls.CommandField does not have a DataBinding event.

After looking at the requirements, i realized that requirements are as simple as replacing text with value from another cell in the same row. There is no need for doing any server side tricks or things like that. I can simple put together a simple client side java script that will take values from cell 1 and put them in whatever cell I want. Abd I came up with this small javascript solution using jQuery. This small code snippet shows how you can manipulate GridView or DataGrid on client side using jQuery. Let me show you the client side javascript that I added on the page. Then I will explain what this code is doing.


<script type="text/javascript">
function updateCommandLinks() {
 var $gridTable = $('#productsGrid');
 var rows = $gridTable.find('tbody > tr');
 var slicedRows = rows.slice(1, rows.length - 2);
 slicedRows.each(function() {
  var cells = $(this).find('td');
  var cellElem1 = cells.get(1);
  var cellElem5 = cells.get(5);
  $(cellElem5).find('a').each(function() {
   $(this).addClass('commandlink').append(" " + cellElem1.innerText);
  });
 });
}

$(document).ready(function() {
  updateCommandLinks();
});
</script>

The above code may look little verbose considering you can write very concise code using jQuery. But for sale of explaining and debugging, I decided to make it little bit verbose. I am sure you can reduce it to half the lines of code that I have written.

The implementation adds a handler for document load event. In that event handler here are the steps it follows:

  1. Finds the element that has id of productsGrid. In our case, that is HTML element ID of our grid view.
  2. In the table, it gets collection of all the rows, identified by tr tag.
  3. Since in my implementation I have header and pager, that adds three rows into the collection. One top row for the header and then the last row itself will contain another table that contains a row for paging elements. To keep it simple, I decided to use slice function to remove first and last 2 rows from collection. You will need to modify this implementation depending on your grid rendering.
  4. It iterates over each row in the collection.
  5. For each row it then finds all cells, identified by td tag.
  6. In my case, I want to replace text in command links with text from second column. So I saved reference to cell at index 1 by using get function.
  7. Then I extracted all elements with tag a from sixth column.
  8. Then it iterates over collection of anchor a tags and appends text from second cell to text in each of the links.

I think that is a simple implementation that serves the purpose without making any changes on the server side. The attached project has the complete implementation for this grid. This is a Visual Studio 2010 project. But you should be able to copy the script from the page to your implementation.

 

Views: 6235

Tags: , ,

ASP.Net | DataGrid | GridView | JQuery

What JQuery File To Use

by Viper 15. March 2009 17:36

When you go to download JQuery files from the site, you are presented with 3 files that you can download.

  1. JQuery-1.3.2.js
  2. JQuery-1.3.2-vsdoc.js
  3. jquery-1.3.2.min.js

Then you start thinking which one to download use. As far the features or functionality goes, all three files do the same job. The difference is what extra help these 3 files provide.

Lets look at jquery-1.3.2.min.js. If you open this file in editor, you will find that the whole implementation is very cryptic and is presented 2 lines. Well as name suggests, this file has been minified. What this means is that all indentation, line breaks, indentations have been removed. And all function parameter names have also been turned into very short names. This helps in keeping the file size small. You shall be using this file when you deploy your application in production environment.

Next is JQuery-1.3.2.js. If you will open this file, you will notice that all functions and implementation is nicely formatted. And all function and parameter names are very self explanatory and may be long at times. This definitely bloats the size of the file. But this file is very helpful during development stage or for debugging purposes because you can clearly see where the error is what could be cause of the error.

Last one is JQuery-1.3.2-vsdoc.js. Open this file and you will find that each function and parameter has been nicely documented using Visual Studion XML Doc conventions. What this means is that Visual STudio provides nice intellisense support for JQuery implementation. You can see from following screen shot how help documentation pops up when you start writing JQuery code in your page's editor.

When you are developing your web application, you should always use this file in development stage and take advantage of Visual Studio's intellisense. Since Microsoft has adopted JQuery in its MVC framework, I am expecting that Microsoft will contribute to JQuery to add more features and build some tools around to it to help development of ASP.Net application easy using JQuery.

 

Views: 3967

Tags: ,

Javascript | JQuery

Smart Phones Poll

What smart phone do you currently own?





Show Results

Month List

Powered by BlogEngine.NET 2.0.0.49
Theme by Naveen Kohli