(Best practice) How do you put the JSON result in the ASP.net MVC Framework?

I am currently using the awesome Linq 2 Json.net (from newtonsoft), which is a very simple simple tool to generate JSON result programmatically.

But after completing some projects, I stopped and changed my mind, should I generate a JSON result in the controller? I mean, in the .net MVC framework, it provided JSONResult as one of the ViewResult. But should the dispatcher worry about how the result is generated? Or should it just β€œprovide” the data for viewing, and there should be a view to create the necessary output (and formatting)?

Finally, I also heard that using β€œViewData” in the controller might not be a good idea, since the controller talks too much about display / release issues, can any better template or method be used?

+4
source share
3 answers

I think I will justify JSON output in the controller, since JSON is just a form of ViewData, similar to how to use the ViewData dictionary to link to View pages.

And the actual browse page is already displayed or processed by client-side languages. Although one drawback is that the JSON-output controller is completely dependent on the view, yes, you can still change the view to another thing that accepts this JSON as a communication channel, but it is not a good idea if you want to change the client, for example, a desktop application using other channels as a connection (for example, a direct TCP connection or SOAP application, etc.), because the controller is designed for JSON. (True, you can make an adapter for translation).

Thus, to complete it, the JSON rendering in the controller is fine until you plan to use a different platform, showing that the controller has not changed.

+1
source

JSON output is pretty simple in most server languages, I never had a reason (or it was possible to justify trying) to complicate them with templates.

While you can, the amount of overhead is probably a waste. In most cases, rendering templates run the entire subsystem, which must be completed before even starting a business.

The whole idea (to me) about JSON (and AJAX responses in general) is that you can shave off a ton of your server overhead.

+1
source

I usually set my results for JsonResults in the controller itself. I feel this before the / DAL / BLL model to give me / ienumerable data filtered by request, but the controller / view frob and return it. In case JsonResult, the structure handles a piece of view / coding. I would reserve views for formatted text (html) output. Use the built-in handler / result for JSON and File / Image responses. XML output may fail imo anyway.

0
source

Source: https://habr.com/ru/post/1286540/


All Articles