Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid 'null' strings when binding JSON data on client side

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.

like image 223
Valentin V Avatar asked Jun 23 '09 07:06

Valentin V


People also ask

Can a JSON string be null?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

Does JSON use null or none?

One of the changes in RFC 7159 is that a JSON text is not defined as being an object or an array anymore but rather as being a serialized value. This means that with RFC 7159, “null” (as well as “true” and “false”) becomes a valid JSON text. So the JSON text serialized value of a null object is indeed “null”.

How are nulls represented in JSON?

If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null . No braces, no brackets, no quotes.


2 Answers

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

like image 151
Amin Avatar answered Oct 23 '22 04:10

Amin


You could set up custom serialization (see

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.

like image 44
Tom Clarkson Avatar answered Oct 23 '22 03:10

Tom Clarkson