Working example for JavaScriptResult in asp.net mvc

前端 未结 3 2036
梦谈多话
梦谈多话 2020-12-01 16:05

Can somebody provide a working example of JavaScriptResult in asp.net mvc. I understand that it returns javascript which is then executed on the client side and also that th

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 16:40

    Avoid if possible

    JavaScriptResult is considered an anti-pattern that Asp.net MVC introduced (complete separation of concerns), because it couples Controller and View back together to make them dependable on eachother. In a pure Asp.net MVC application where the UI is build on Asp.net MVC and server side serves this client implementation only it is thus advised to avoid this functionality.

    It may be useful in other scenarios. I can remember I've been reading something related to Ruby on Rails clients.

    Anyway.

    An example that does make sense

    An actual example would be to return javascript code to an Ajax request that would simply provide some functionality that will get executed immediately upon response without any data manipulation.

    Where could you possibly benefit from it? Well think of an application that has huge amounts of various client classes used thoughout the application. But certain pages use only a small fraction (or even a dynamic fracion) of them. In this case you would have two possibilities:

    1. Load the whole client class tree upfront - either in a huge single file or fragmented in separate files (this would be ok if views would use a small sub set of up-front known classes, because otherwise this would result in lots of server requests)
    2. Load classes on demand when they are needed - or maybe even execute certain class functions on demand when and if they are needed.

    In this particular case, the second scenario would be much better and much more efficient in terms of network traffic, client memory resources and processor load.

提交回复
热议问题