ASP.NET MVC3 How to reference views directly from

2019-04-29 05:56发布

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);
    }

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-29 06:40

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 and T4MVC.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

@Html.RenderPartial("DinnerForm");

Would be:

@Html.RenderPartial(MVC.Dinners.Views.DinnerForm);

This:

@Html.ActionLink("Delete Dinner", "Delete", "Dinners", new { id = Model.DinnerID }, null)

Would Be this instead:

@Html.ActionLink("Delete Dinner", MVC.Dinners.Delete(Model.DinnerID))

This :

<img src="/Content/nerd.jpg" />

Would be this instead:

<img src="@Links.Content.nerd_jpg" />

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.

查看更多
登录 后发表回答