Thursday, October 29, 2009

JQuery pass parameter to event handler

How can you pass values into a event handler, plain and simple?

here it is!

var somevar = 'value'; //declare some var

And here comes the magic, on the bind function, in the second parameter, you define the data structure to pass on to your anonymous event handler (which can be multiple parameters, comma separated).
(notice that you have to receive the event parameter on the handler function, so you can access the data you sent)

$("something").bind("click", { data: somevar }, function(event) { //this is the way you can access it on the handler function

So, what's the use of this? you can send data that is accessible in your current context, where you are defining the handler, but inside the handler it's unreachable.

Hope this is as useful for you as it was for me!

See you soon :)

Wednesday, October 28, 2009

Deserialize JSON with C#

You're using JQuery, making some fancy ajax requests, but tired of Request["setting"] to get data from client-side, starving for a strong-typed approach? STOP! I've got just what you need, and supports single object, and even lists of objects (arrays)!


Single: { "field1":"value1","field2":"value2" }
Array: [ { "field1":"value1","field2":"value2" }, { "field1":"value1","field2":"value2" } ]

For the single, the .NET Framework has the key, you need to create a class that has public fields or properties matching the field names on your JSON string, example:

public class Test
public string field1 { get; set; }
public string field2 { get; set; }

And the code to serialize your Single JSON is this:

Test myDeserializedObj = (Test)JavaScriptConvert.DeserializeObject(Request["jsonString"], typeof(Test));       

and voilá! you got yourself a strong-typed object with client-side data, sweet!

But and if I want a list of data of the same type, say an Array, how is it done? The .NET Framework hasn't got the answer for this one..
You have to download and reference the following DLL

Once it's done:

List< test > myDeserializedObjList = (List< test >)Newtonsoft.Json.JsonConvert.DeserializeObject(Request["jsonString"], typeof(List< test >));

and yes! you're done :)

How easy is this? It's perfect for your lightweight ajax applications with .NET backend.

Please post comments!

See you soon

Tuesday, October 27, 2009

JQuery and XML

Today I've started to use JQuery for XML navigation for the first time. For what I've seen it seems that it is pretty easy, just like using it for HTML, like:

$(xml).find('element').each(function() {
//do something
$('some html element').append($(this).find('nested element').attr('test'));

nice hã?