I have the following class on my server:
public class JsonDialog
{
public IEnumerable<string> Errors { set; get; }
public string Modified { set; get; }
public string ModifiedBy { get; set; }
public string PartitionKey { set; get; }
public string PartitionKeyNew { set; get; }
public string RowKey { get; set; }
public string RowKeyNew { get; set; }
public bool Success { set; get; }
}
In my MVC action method I return a JsonResult:
return Json(new JsonDialog
{
Success = false,
Errors = errors
});
In my client code I have the following:
$.ajax({
url: href,
dataType: 'json',
type: 'POST',
data: $form.serializeArray()
})
.done(onDone)
.fail(onFail);
var onDone = function (json, textStatus, XMLHttpRequest) {
json = json || {};
if (json.Success) {
Because I am using a class on the server the compiler checks to ensure I don’t make any spelling mistakes and for example it will not allow me to enter “success = false”. However on the client there’s no checking and I could code json.sUccEss and it would still be okay with that but it would not give me the desired result.
Is there any way in Javascript that I can have some error checking like I have on the server? Anything like getting data into a class and having the IDE check that class fields are correct?
I solve this (partially) by creating a matching object in JS with, what I refer to as a ‘factory’ method (but that’s a misnomer if you’re using the term ‘factory’ as is referred to here. It’s really more analogous to ‘casting’, but since JS doesn’t have strong typing, that’s not exactly right either.
Obviously, this code pattern is also pretty verbose if all you’re doing is trying to get intellisense working, but if you have methods on your JS-side object… we’ll fictionally say:
JsonResult.prototype.markErrorsReviewed…then this pattern where you get an instance of a given ‘class’ is helpful.For the sake of brevity, I’m going to just use your C# class on which to base my JS:
AJAX: