@Url.Content 使用 ASPNET MVC 3 和 Razor 在单独的 javascript 文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7663486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:06:41  来源:igfitidea点击:

@Url.Content in separate javascript file using ASPNET MVC 3 and Razor

javascriptasp.net-mvcgoogle-maps-markers

提问by polonskyg

I was using this

我正在使用这个

if (ret = 1)
    iconType = new google.maps.MarkerImage('@Url.Content("~/Content/images/image.png")');
else if (ret = 2)
    iconType = new google.maps.MarkerImage('@Url.Content("~/Content/images/image2.png")');
else if (ret = 3)
    iconType = new google.maps.MarkerImage('@Url.Content("~/Content/images/image3.png")');

in a View (ASPNET MVC 3), now I'm moving the code to a separate javascript file (I'm using that because depending on a vaiable value I set as image of a control image.png, image2.png or image3.png).

在视图 (ASPNET MVC 3) 中,现在我将代码移动到一个单独的 javascript 文件中(我使用它是因为根据我设置为控件 image.png、image2.png 或 image3 的图像的可变值。 .png)。

Razor doesn't parse @Url.Content inside javascript file, What's the best way to handle this?

Razor 不会解析 javascript 文件中的 @Url.Content,处理这个问题的最佳方法是什么?

Thanks in advance! Guillermo.

提前致谢!吉列尔莫。

回答by AHM

I usually put a block like this in the beginning of the page:

我通常在页面的开头放一个这样的块:

<script>
    var ROOT = '@Url.Content("~")';
</script>

And then i refer to the ROOTvariable in javascript:

然后我指的ROOT是 javascript 中的变量:

if (ret = 1)
    iconType = new google.maps.MarkerImage(ROOT + '/Content/images/image.png');
else if (ret = 2)
    iconType = new google.maps.MarkerImage(ROOT + '/Content/images/image2.png');
else if (ret = 3)
    iconType = new google.maps.MarkerImage(ROOT + '/Content/images/image3.png")');

回答by Beriz

Another solution is rendering your JS files completely through the RazorViewEngine. This way you could easily use the Razor Syntax within your Javascript file:

另一种解决方案是完全通过 RazorViewEngine 渲染您的 JS 文件。通过这种方式,您可以轻松地在 Javascript 文件中使用 Razor 语法:

public class CustomRazorViewEngine : BuildManagerViewEngine
{
    internal static readonly string ViewStartFileName = "_ViewStart";

    public CustomRazorViewEngine()
        : this(null)
    {
    }

    public CustomRazorViewEngine(IViewPageActivator viewPageActivator)
        : base(viewPageActivator)
    {
        AreaViewLocationFormats = new[]
                                    {
                                        "~/Areas/{2}/Views/{1}/{0}.cshtml",
                                        "~/Areas/{2}/Views/{1}/{0}.vbhtml",
                                        "~/Areas/{2}/Views/{1}/{0}.csjs",
                                        "~/Areas/{2}/Views/Shared/{0}.cshtml",
                                        "~/Areas/{2}/Views/Shared/{0}.vbhtml",
                                        "~/Areas/{2}/Views/Shared/{0}.csjs"
                                    };
        AreaMasterLocationFormats = new[]
                                        {
                                            "~/Areas/{2}/Views/{1}/{0}.cshtml",
                                            "~/Areas/{2}/Views/{1}/{0}.vbhtml",
                                            "~/Areas/{2}/Views/{1}/{0}.csjs",
                                            "~/Areas/{2}/Views/Shared/{0}.cshtml",
                                            "~/Areas/{2}/Views/Shared/{0}.vbhtml",
                                            "~/Areas/{2}/Views/Shared/{0}.csjs"
                                        };
        AreaPartialViewLocationFormats = new[]
                                            {
                                                "~/Areas/{2}/Views/{1}/{0}.cshtml",
                                                "~/Areas/{2}/Views/{1}/{0}.vbhtml",
                                                "~/Areas/{2}/Views/{1}/{0}.csjs",
                                                "~/Areas/{2}/Views/Shared/{0}.cshtml",
                                                "~/Areas/{2}/Views/Shared/{0}.vbhtml",
                                                "~/Areas/{2}/Views/Shared/{0}.csjs"
                                            };

        ViewLocationFormats = new[]
                                {
                                    "~/Views/{1}/{0}.cshtml",
                                    "~/Views/{1}/{0}.vbhtml",
                                    "~/Views/{1}/{0}.csjs",
                                    "~/Views/Shared/{0}.cshtml",
                                    "~/Views/Shared/{0}.vbhtml",
                                    "~/Views/Shared/{0}.csjs"
                                };
        MasterLocationFormats = new[]
                                    {
                                        "~/Views/{1}/{0}.cshtml",
                                        "~/Views/{1}/{0}.vbhtml",
                                        "~/Views/{1}/{0}.csjs",
                                        "~/Views/Shared/{0}.cshtml",
                                        "~/Views/Shared/{0}.vbhtml",
                                        "~/Views/Shared/{0}.csjs"
                                    };
        PartialViewLocationFormats = new[]
                                        {
                                            "~/Views/{1}/{0}.cshtml",
                                            "~/Views/{1}/{0}.vbhtml",
                                            "~/Views/{1}/{0}.csjs",
                                            "~/Views/Shared/{0}.cshtml",
                                            "~/Views/Shared/{0}.vbhtml",
                                            "~/Views/Shared/{0}.csjs"
                                        };

        FileExtensions = new[]
                            {
                                "cshtml",
                                "vbhtml",
                                "csjs",
                            };
    }

    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
    {
        return new RazorView(controllerContext, partialPath,
                             layoutPath: null, runViewStartPages: false, viewStartFileExtensions: FileExtensions,
                             viewPageActivator: ViewPageActivator);
    }

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        var view = new RazorView(controllerContext, viewPath,
                                 layoutPath: masterPath, runViewStartPages: true, viewStartFileExtensions: FileExtensions,
                                 viewPageActivator: ViewPageActivator);
        return view;
    }
}

In Your Global asax file just add these:

在您的全局 asax 文件中,只需添加以下内容:

RazorCodeLanguage.Languages.Add("csjs", new CSharpRazorCodeLanguage());
ViewEngines.Engines.Add(new CustomRazorViewEngine());

And add this mapping in the web.config root

并在 web.config 根目录中添加此映射

   <system.web>
          <compilation debug="true" targetFramework="4.0">
                 <assemblies>
                       <add assembly="Newtonsoft.Json" />
                       <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                       <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                       <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                       <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                       <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                 </assemblies>

                 <!--Added-->
                 <buildProviders>
                       <add extension=".csjs" type="System.Web.WebPages.Razor.RazorBuildProvider, System.Web.WebPages.Razor"/>
                 </buildProviders>

You can now even work with a Model inside your javascript file!

您现在甚至可以在 javascript 文件中使用模型!

public ActionResult MyJavascriptThroughRazor()
{
    var someModel = ...
    return PartialView("filenamewithcsjsextension",someModel);
}