The JsonResult class is a very useful way to return Json as an action to the client via AJAX.
public JsonResult JoinMailingList(string txtEmail)
{
// ...
return new JsonResult()
{
Data = new { foo = "123", success = true }
};
}
However (at least according to my first impression) this really isn't a good separation of concerns.
- Unit test methods are harder to write becasue they don't have nice strongly typed data to test and have to know how to interpret the Json.
- Its harder for some other View in future that isn't over HTTP (or any remote protocol involving serialization) to be 'plugged in' because its unnecessary in such cases to be serializing and deserializing the response.
- What if you have TWO different places that need the results of that action? One wants Json and another wants XML or perhaps a fully or partially rendered view.
I'm wondering why the translation between an object and Json wasn't implemented declaratively via an attribute. In the code below you're essentially telling MVC that this method is convertible to Json
, and then if it is called from an AJAX client a check is made for the attribute the new JsonResult()
conversion performed internally.
Unit testing can just take the action result (ObjectActionResult
) and pull out the strongly typed Foo
.
[JsonConvertible]
public ActionResult JoinMailingList(string txtEmail)
{
// ...
return new ObjectActionResult()
{
Data = new Foo(123, true)
};
}
I was just curious as to people's thoughts and any alternative pattern to follow.
These are also just my initial observations - there are probably more reasons why this is not an ideal design (and probably plenty why its a perfectly acceptable and practical one!) I'm just feeling theoretical and devils-advocatey tonight.
* Disclaimer: I haven't even begun to think about how the attribute would be implemented or what sideeffects or repurcussions etc. it might have.