【问题标题】:How to avoid using hard coded string literals when invoking, for example, RedirectToAction?如何在调用时避免使用硬编码字符串文字,例如 RedirectToAction?
【发布时间】:2017-04-28 06:38:18
【问题描述】:

在调用Html.DisplayNameFor 时,我们只需提供一个 lambda 表达式来呈现,例如通过item => Model.Name 呈现学生姓名。 由于编译时检查,这种方法非常好。

如何使RedirectToAction 也成为可能,例如RedirectToAction(controller => Controllers.Student.Index) 而不是RedirectToAction("Index")?假设名为 Controllers 的属性包含项目中使用的所有控制器。

【问题讨论】:

  • 看看这个:stackoverflow.com/questions/2102757/… 虽然这些库看起来很旧,但我不知道它们是否仍然适用于最新版本的 ASP.NET
  • 如果属性 Controllers.Student.Index 是正确的(或者你可以得到类似的属性),你可以简单地使用 RedirectToAction(nameof(Controllers.Student.Index))

标签: c# asp.net


【解决方案1】:

你可以。

作为变体 - 从 ControllerBase 创建 CoolControllerBase 继承者并添加 Controllers 属性。所有控制器都应该继承 CoolControllerBase。在静态构造函数中使用反射填充 Controllers 属性:GetAssembly、GetClasses 继承 CoolControlelrBase、GetMethods 用于每个类。

其他变体 - 使用 Roslyn 实现相同的效果。

第三种变体:使用 nameof。

RedirectToAction(nameof(Student), nameof(Student.Index)) 

但是你的目标是什么?你想要自动完成吗?

【讨论】:

  • 我想获得编译时检查和 IntelliSense 支持。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 2017-04-29
  • 2013-03-16
  • 2016-03-27
  • 2019-09-22
  • 2018-11-19
相关资源
最近更新 更多