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 generally try not to worry about it. The Asp.Net MVC is enough of a separation of concerns to keep leakage to a minimum. You're right though; there is a bit of a hurdle when testing.
Here's a test helper I use, and it's worked well:
protected static Dictionary GetJsonProps(JsonResult result)
{
var properties = new Dictionary();
if (result != null && result.Data != null)
{
object o = result.Data;
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(o))
properties.Add(prop.Name, prop.GetValue(o) as string);
}
return properties;
}
You can use the Request.IsAjaxRequest() extension method to return different ActionResult types:
if (this.Request != null && this.Request.IsAjaxRequest())
return Json(new { Message = "Success" });
else
return RedirectToAction("Some Action");
Note: you'll need that Request != null to not break your tests.