views:

532

answers:

3

Is it possible to avoid having 'NULL' stings on the client when binding JSON data to HTML UI?

I'm using ASP.NET MVC + jQuery + jTemplates. Data is coming from linq-to-sql classes and these classes have quite a lot of nullable properties. When such properties get serialized and transferred back to client I end up with such JSON:

[{"Id":1,"SuitId":1,"TypeId":null,"Type":null,"CourtId":null,"Court":null}]

Whey I bind this data to HTML I have a lot of 'NULL' strings. I've tried both manual binding and JavaScript templating engines (jTemplate). Results are the same. Currently I'm dealing with this issue by 'coalescing' the null values as follows:

$('#Elem').val(someVar||'');

But I don't want to do it manually.

Please advice if I:

  1. Can automatically translate nullable properties to empty strings by either tweaking the serialization process or maybe choosing the 3rd party JSON serializer over .NET JSON serializer.
  2. Can do anything on client side, such as working around this with either jQuery or templating engines.

Thank you.

+1  A: 

I tend to ask myself at what point is the data incorrect? Is is incorrect to say the TypeId is null (unknown, not assigned) when it should specifically be assigned '' (empty string)?

In this case I would guess not, what is incorrect it the way the presentation displays "null", you want simply an empty textbox or some such thing. In this case its the presentations problem to convert the data to a view that is acceptable, thats its job. Hence your use of "coalescence" seems correct to me.

Of course thats perhaps an overly strict interpretation and may not be as pragmatic as you would like. In the long run though (I mean over the code's lifetime) it usually best to keep things as correct as they can pratically be.

AnthonyWJones
+2  A: 

You could set up custom serialization (see

http://stackoverflow.com/questions/159704/how-to-implement-custom-json-serialization-from-asp-net-web-service )

You could also make your own version of val that converts null to an empty string. However, I think that the method you are currently using is probably better anyway - the generic methods could add a lot of complexity and possibly hidden bugs.

Tom Clarkson
+1  A: 

You can modify jtemplate to return an empty string instead of null by modifying the follow line of code in jquery.jtemplate.js.

First find this function

TemplateUtils.cloneData = function(d, filter, f_escapeString) {

The very next block of code is an if statement

if (d == null) {
    return d;
}

Modify that to

if (d == null) {
   return "";
}

And that should do it

Amin
Nice work, very clever. Saved me a great deal of effort.
Gregory