Reputation: 25749
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.
Upvotes: 6
Views: 4307
Reputation: 446
For jTemplates only, this is what I did:
{#if $T.mylist.nullableProperty != null}{$T.myList.nullableProperty}{#/if}
Upvotes: 0
Reputation: 31
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
Upvotes: 3
Reputation: 16174
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.
Upvotes: 2
Reputation: 189457
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.
Upvotes: 1