Using C# 6's using static syntax in MVC App_Co

2019-02-28 09:55发布

问题:

Is it possible to use C# 6.0's new "using static" notation inside of display helpers in App_Code in MVC 5?

I attempted to do so but it did not seem to like the syntax.

I created a static helper class to expose UrlHelper and HtmlHelper within App_Code. I was hoping to include it with the "using static" syntax in order to use the properties of the class as I would as if the file had a ViewPage base class.

@using static Example.Core.ViewHelper

@helper ExampleUsingUrl() {
    @Url.Action("Index", "Home")
}

With a ViewHelper looking like this.

namespace Example.Core
{
    public static class ViewHelper
    {
        public static HtmlHelper Html { get; } = new HtmlHelper(new ViewContext(), new ViewDataContainer());
        public static UrlHelper Url => new UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes); 
    }

    public class ViewDataContainer : IViewDataContainer
    {
        public ViewDataDictionary ViewData
        {
            get
            {
                return new ViewDataDictionary();
            }
            set
            {

            }
        }
    }
}

Is this feature not available for views yet? I am using Visual Studio 2015, MVC 5, .NET 4.6.1 and C# 6.0.

回答1:

This is not possible in MVC5 but MVC6.

See code change for supporting using static in MVC6: https://github.com/aspnet/Razor/commit/1879ac642754b5f84e6055580e6fc60e13fa2100



回答2:

I think I'm using mvc 5 and it's working for me. System.Web.Mvc.dll version 5.2.3.0

I'm running this in VS 2015 which uses c# 6.0. So it's either that or the version 5.2.3.0 that's doing it.

So the answer by Kevin it may not be 100% correct.

MVC 6 is not "stable" in a very broad sense of the word so we are using MVC5 atm.

Note that at first it didn't find my static reference, but there was no squiggly. After cutting and repasting the "@using static" line a few times it started working. I can navigate to definition on my static extension method.