2

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.

4
  • I built a custom tool that does static analysis of assebmlies to find controllers, and build a new static type with string properties that map to the actions each build, then use that type instead of strings. If an action is removed or renamed it generates a compile time error after a rebuild from the tool. I don't know if that's an option for you but it worked ok for my small-ish mvc3 project.
    – asawyer
    Jan 16, 2013 at 13:34
  • 1
    @Html.RenderPartial() is the method I use for rendering Partial Views...
    – Richard A.
    Jan 16, 2013 at 13:35
  • 1
    Have a look at T4MVC and FluentHtml to eliminate magic strings.
    – StuartLC
    Jan 16, 2013 at 13:38
  • @RichardA., I'm using Action since I would need the partial view to be cached Jan 16, 2013 at 13:52

1 Answer 1

2

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.