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:
Thank you.
JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
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”.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With