Should my MVC controller really know about JSON?

后端 未结 7 2091
有刺的猬
有刺的猬 2021-01-30 14:51

The JsonResult class is a very useful way to return Json as an action to the client via AJAX.

public JsonResult JoinMailingList(string txtEmail)
{
        // ...         


        
7条回答
  •  渐次进展
    2021-01-30 15:11

    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.

提交回复
热议问题