在剃刀视图中为操作 URL 设置变量是一种好做法吗?我可以将它们放在 ViewModel 中吗?

Is having variables for action URLs in a razor views a good practice? Can I put them in the ViewModel?

我正在努力获得更清晰的视图,以便于阅读和修改。

我通常为每个视图设置几个变量,表示其中使用的操作 URL:

    @model IndexViewModel
    
    @{
        // controllers
        string newsControllerName = nameof(NewsController).ToName();
    
        // calls to actions
        string removeNewsActionUrl = Url.Action(nameof(NewsController.RemoveNews));
        string getNewsActionUrl = Url.Action(nameof(NewsController.GetNews));
        string indexActionUrl = Url.Action(nameof(NewsController.Index));
    } 

所以我可以在 JavaScript:

中的 ajax 调用的视图数据属性中使用它们
    <div id="newsContainer"
         data-remove-url="@removeNewsActionUrl"
         data-view-url="@getNewsActionUrl">
        ...
    </div>

然后我的一个朋友建议我不应该在视图中声明变量,因为这是一种不好的做法,为什么不在该视图的 ViewModel 中声明它们,在这种情况下 IndexViewModel.

我知道视图不应该有复杂的逻辑并且应该有最少的 C# 代码,但我正在做的是不是一种不好的做法?如果是,为什么?为此,在该视图的 ViewModel 中声明变量是否有缺点或优点?

来自 Microsoft docs 个视图和视图模型:

Views are responsible for presenting content through the user interface. They use the Razor view engine to embed .NET code in HTML markup. There should be minimal logic within views, and any logic in them should relate to presenting content. If you find the need to perform a great deal of logic in view files in order to display data from a complex model, consider using a View Component, ViewModel, or view template to simplify the view.

我在此站点上找不到与此相关的任何内容。

我不想在视图模型中使用这些东西。它是多余的,因为模型和控制器之间没有任何通信。

我看不出这有什么问题 - 这是最小的逻辑,它纯粹与视图本身有关。将它放在其他任何地方都会无缘无故地污染代码库的另一部分。

也就是说,我真的没有看到代码块有什么好的理由 - 为什么不直接将它内联到 HTML 属性中呢?