Should my MVC controller really know about JSON?

后端 未结 7 1983
有刺的猬
有刺的猬 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:05

    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 HtmlFormatters 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 HtmlFormatters) 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.

提交回复
热议问题