Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I prefer writing my server layer as an API emitting JSON - in ASP.NET MVC that's real simple - you just create a bunch of nested anonymous objects, and <code>return Json(data);</code>. The JSON object is then consumed by the client layer, which consists of html, css and javascript (I use jQuery a lot, but you might prefer other tools).</p> <p>Since javascript is dynamic, it is then real easy to just have a property <code>status</code> on the data object, and the client side script can interpret that and display status or error messages as needed.</p> <p>For example, consider the following action method:</p> <pre><code>public ActionResult ListStuff() { var stuff = Repo.GetStuff(); return Json(new { status = "OK", thestuff = stuff }); } </code></pre> <p>This will return JSON in the following format:</p> <pre><code>{ "status": "OK", "thestuf": [{ ... }, { ... }] } </code></pre> <p>where <code>...</code> is a placeholder for the properties of <code>stuff</code>. Now, if I want error handling, I can just do</p> <pre><code>try { var stuff = Repo.GetStuff(); return Json(new { status = "OK", thestuff = stuff}); } catch (Exception ex) { Log.Error(ex); return Json(new { status = "Fail", reason = ex.Message }); } </code></pre> <p>Since javascript is dynamic, it doesn't matter that the two anonymous objects don't have the same properties. Based on the value of <code>status</code>, I'll only look for properties that are actually there.</p> <p>This can be implemented even better if you create your own action result classes, which extend <code>JsonResult</code> and add the status property automatically. For example, you can create one for failed requests that takes an exception in the constructor and one for successful ones than take an anonymous object.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload