ASP.NET MVC3 如何直接从控制器引用视图
在我的控制器中,我想指定一个与默认值不同的视图。 像这样:
public ActionResult EditSurvey(Int32 id)
{
Survey survey = _entities.Surveys.Single(s => s.Id == id);
return View("Survey",survey);
}
但是我不想将视图指定为字符串(“调查”),而是直接引用它,因此如果我决定稍后更改视图的名称,则不必手动更改此字符串。
所以我正在寻找这样的东西:
public ActionResult EditSurvey(Int32 id)
{
Survey survey = _entities.Surveys.Single(s => s.Id == id);
return View(Views.Admin.Survey,survey);
}
In my controller I want to specify a different View than default.
Like this :
public ActionResult EditSurvey(Int32 id)
{
Survey survey = _entities.Surveys.Single(s => s.Id == id);
return View("Survey",survey);
}
But instead of specifying the view as a string ("Survey") I would like to reference it directly, so if I decide to change the name of my view later on I don't have to change this string manually.
So I'm looking for something like this :
public ActionResult EditSurvey(Int32 id)
{
Survey survey = _entities.Surveys.Single(s => s.Id == id);
return View(Views.Admin.Survey,survey);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好问题,没有内置支持,因为
View()
方法需要一个字符串,但是有一个名为 T4MVC 由 David Ebbo 创建就是这么做的。codeplex 上的文档有一个手动安装过程,我建议直接从 VS2010 使用 NuGet 包管理器获取它。
它非常简单,整个事情就是您可以添加到项目中的文件。 (
T4MVC.tt
和T4MVC.settings.t4
),每次更改代码时,(1) 右键单击 T4MVC.tt 并< strong>(2) 点击“运行自定义工具”。它的作用是为所有控制器和视图生成一个包含子类、成员、属性的类。它甚至所做的是为所有内容创建强类型,例如图像、CSS、JS 等。(我认为这非常棒)
示例:
这
将是:
这:
将是这样:
这:
将是这样:
您必须右键单击
tt
文件和“运行自定义工具”,如之前每次更改视图、控制器时提到的,但是,如果您想自动执行此操作,看看 Chirpy,它可以做到这一点,甚至更多。(注意 T4MVC 在文档中有 aspx/mvc2 示例,但在 MVC3 上运行良好,因为我在生产中使用 MVC3/Razor 应用程序)
另请参阅 T4MVC 标签 上的 SO。
Good question, there is no inbuilt support as the
View()
method expects a string, but there is a Nifty tool called T4MVC created by David Ebbo that does just that.The documentation on codeplex has a manual install procedure, I would recommend getting it with NuGet package manager straight from VS2010.
Its pretty simple, the whole thing is files which you can just add to your project. (
T4MVC.tt
andT4MVC.settings.t4
), everytime you change your code, (1) Right-click T4MVC.tt and (2) Click "Run Custom Tool".What it does is generate a class with Subclasses, Members, Properties for all your Controllers and Views. What it even does is create strong types for all your content, like images, css, js etc. (Which I think is just awesome)
Examples:
This
Would be:
This:
Would Be this instead:
This :
Would be this instead:
You do have to Right-Click on the
tt
file and "Run Custom Tool" as mentioned before every time you change your views, controllers, however, if you want to automate this, Check out Chirpy which does that and more.(Note T4MVC has aspx/mvc2 examples on the docs but works fine on MVC3 as I use in production with a MVC3/Razor app)
Also see T4MVC tag on SO.