gpt4 book ai didi

c# - 为什么 'JavaScript' 或 'JavaScriptResult' 是反模式?

转载 作者:行者123 更新时间:2023-11-30 17:44:43 26 4
gpt4 key购买 nike

我读到 MVC 的 JavaScriptResult 是一种反模式。

基本解释是 Controller 必须了解 View ,这就是为什么它是反模式的原因。

我希望有人能更详细地描述正在发生的事情以及它为什么不好。

很多人都提到了this blog , 但我得到了 503...

例子:

[HttpPost]
public ActionResult SomeMethod()
{
return JavaScript("window.location = '/url';");
}

最佳答案

感谢@GrawCube link .

全文如下。

Beware of ASP.NET MVC JavaScriptResult

One of the immense advantages that ASP.NET MVC has over classic ASP.NET is the clean separation of concerns between the presentation and controller logic. Unfortunately, while the MVC RC has brought with it many improvements, it has also taken a step towards breaking down the clean separation of concerns with the introduction of the JavaScriptResult ActionResult. Per the release notes, "the JavaScriptResult class is used to execute JavaScript code that is created on the server and sent to the client." The release notes even go as far to include the following code example:

public ActionResult DoSomething() 
{
script s = "$('#some-div').html('Updated!');";
return JavaScript(s);
}

While I can surmise that there is more than one useful scenario for the inclusion of JavaScriptResult, the above example should be seen as an anti-pattern of its use. This example is introducing a very fragile dependency into the controller on the view itself. In classic ASP.NET, the code-behind page was able to have strongly typed access to elements in the view. In the above scenario, a similar dependency is introduced into the controller, but now it's not even strongly typed.

Like extension methods and lambda expressions, JavaScriptResult puts more power into the hands of the developer, but also assists in shooting yourself in the foot if used improperly. So like any powerful .NET tool, have a good reason to use it, keep an eye on proper separation of concerns, and always keep testability and maintainability strongly in your design.

Billy McCafferty

关于c# - 为什么 'JavaScript' 或 'JavaScriptResult' 是反模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29130173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com