ASP.Net MVC Action methods compile time errors in

2019-02-27 13:14发布

问题:

e Is there any way where one can produce compile time errors if an action method is not available in the controller through using the Html.Action?

For example, let us say we have a controller named LayoutMainPartialViewsController and within such a controller, we have a method Header which outputs the Header Partial View located at /Views/Shared/PartialViews/_Header.cshtml

public class LayoutMainPartialViewsController : Controller
{
    //
    // GET: /LayoutMainPartialViews/

    public ActionResult Header()
    {
        return PartialView("/Views/Shared/PartialViews/_Header.cshtml");
    }

}

Then to include such partial view, we would call within Razor

@Html.Action("Header", "LayoutMainPartialViews");

If for some reason, the method named Header is renamed to Header2, no compile time errors are given but only run time errors.

I would like to be able to have compile time errors to minimize as much as possible runtime errors as they are much more difficult to identify.

On another note, would it make sense to call something like?

@(new LayoutMainPartialViewsController().Header())

The method above returns an ActionResult which needs to be converted as String the same way Html.Action does.

This way, if we change Header to Header2 and have <MvcBuildViews>true</MvcBuildViews> in the csproj, an error is provided compile time.

回答1:

T4MVC is a T4 template for ASP.NET MVC apps that creates strongly typed helpers that eliminate the use of literal strings in many places.

This does exactly what I require and removes the usage of 'magic strings' as opposed to strongly typed identifiers. Compile time errors are provided even in views if the <MvcBuildViews>true</MvcBuildViews> is set to true.

Thanks @StuartLC for the tip!