For those of you who are (un)fortunate enough to do web development you will probably run into the issue of wanting to move a .NET DTO and be able to access it in JavaScript. The simple way to do this is to use JSON (I know this is nothing new but a lot of people have not heard of this technology). JSON stands for the JavaScript Object Notation and is a simple string representation of an object that can be parsed using the JavaScript eval() method.
Simply the way this works is that a .NET library (I am using the free newtonsoft library in my project) takes an object and serializes it to a string. We then call var object = eval(serializedString) and then we can access all the properties off the object (and it seriously is that simple).
.NET Code:
public interface IResource
{
IList<IResource> Resources { get; set; }
string Name { get; }
bool IsOnline { get; }
void Check();
}
public string GetServers()
{
return Newtonsoft.Json.JavaScriptConvert.SerializeObject(resource);
}
JavaScript Code:
function ShowObject(input)
{
var resource = eval("(" + input + ")");
document.getElementById("txtName").value = resource.Name;
document.getElementById("chkIsOnline").checked = resource.IsOnline;
//we could actually walk resource.Resources in a recursive fashion here as even the
//child collections get serialized and sent across the wire.
}
And it is just that easy. You can also modify the object in JavaScript and return it to .NET and call JavaScriptConvert.DeserializeObject() and have the object back in the .NET form and process it. The possibilities for this are quite powerful.
I would watch for security issues with this though as calling eval on a string with JavaScript can be quite dangerous if the input is not validated properly! This is because the eval() function evaluates a string and executes it as if it was JavaScript so the injection of dangerous code is a very simple possibility.