The JsonResult class is a very useful way to return Json as an action to the client via AJAX.
public JsonResult JoinMailingList(string txtEmail)
{
// ...
I think you're getting worked up over nothing. So what if the controller knows about JSON in its public interface?
I was once told: "Make your code generic, don't make your application generic."
You're writing an Application Controller here. It's OK for the Application Controller - whose responsibility is to mitigate between the model and views and to invoke changes in the model - to know about a certain view (JSON, HTML, PList, XML, YAML).
In my own projects, I usually have something like:
interface IFormatter {
ActionResult Format(object o);
}
class HtmlFormatter : IFormatter {
// ...
}
class JsonFormatter : IFormatter {
// ...
}
class PlistFormatter : IFormatter {
// ...
}
class XmlFormatter : IFormatter {
// ...
}
Basically "formatters" that take objects and give them a different representation. The HtmlFormatter
s are even smart enough to output tables if their object implements IEnumerable
.
Now the controllers that return data (or that can generate parts of the website using HtmlFormatter
s) take a "format" argument:
public ActionResult JoinMailingList(string txtEmail, string format) {
// ...
return Formatter.For(format).Format(
new { foo = "123", success = true }
);
}
You could add your "object" formatter for your unit tests:
class ObjectFormatter : IFormatter {
ActionResult Format(object o) {
return new ObjectActionResult() {
Data = o
};
}
}
Using this methodology, any of your queries/actions/procedures/ajax calls, whatever you want to call them, can output in a variety of formats.