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

asp.net-mvc, javascript, jquery, json

Solution

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.

Problem

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: - 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. - Can do anything on client side, such as working around this with either jQuery or templating engines. Thank you.

Original source