How do I use @Url.Content() in non-MVC Razor webpage?

淺唱寂寞╮ 提交于 2020-01-15 12:14:28

问题


Since I'm using Web Application having NuGet Package's Microsoft.AspNet.Razor installed.

In WebForm pages (.aspx), I can use ResolveUrl() but in Razor pages (.cshtml), I get this error -->

"x:\Source\Foo.Dealer\Foo.Dealer.WebApp.Mobile\Member\DmsDashboard.cshtml(103): error CS0103: The name 'Url' does not exist in the current context"

Source-Code here..

@section HeadJavascriptLibraryFile
{
    <script type="text/javascript" src="@Url.Content("~/scripts/webpages/setting-dmsdashboard.js")"></script>
}

and

<img src="@(Url.Content("~/images/miscellaneous/reportandpiechart2.png"))" alt="" />

Source Code as requested...

//LayoutMembmerGeneral.cshtml
@using Foo.Dealer.WebApp.Mobile.Infrastructure;
@{
    if (LoginManagementTools.DealerUserLoginValidation_BrowsingPage(HttpContext.Current.Request, HttpContext.Current.Response, HttpContext.Current.Session) == false) { }
}<!DOCTYPE html>
<html>
<head>
  <title>@Page.Title</title>
  @RenderSection("HeadJavascriptLibraryFile", false)
</head>
<body>
@RenderBody()
</body>
</html>

//DmsDashboard.cshtml...
@using Foo.Dealer.WebApp.Mobile.Infrastructure
@using System.Web.Mvc;

@{
    Page.Title = "A New Dawn In Auto Pricing";
    Layout = "LayoutMemberGeneral.cshtml";
}
@section HeadJavascriptLibraryFile
{
}

<div id="WebLayout1">
    <img src="@Url.Content("images/miscellaneous/reportandpiechart2.png")" alt="" />
</div>

回答1:


The URL helper doesn't seem to exist in ASP.Net Web Pages (which is essentially what you are attempting to do), but you can simply use the following code to achieve the same effect:

<img src="~/images/miscellaneous/reportandpiechart2.png" alt="" />

The tilde (~) references the application root and is transformed when the page is compiled and sent to the client.




回答2:


The tilde (~) is not transformed as part of any data- attributes and likely, other places also, though I haven't researched extensively.

If you happen to need this information in a place where the automatic transofmration isn't working, you can use the tilde equivalent, HttpContext.Current.Request.ApplicationPath.

In most Razor views, you should be able to shorten it to the following:

@Request.ApplicationPath

Reference: http://msdn.microsoft.com/en-us/library/system.web.httprequest.applicationpath.aspx

Another alternative in some situations is to use the VirtualPathUtility such as:

@VirtualPathUtility.ToAbsolute("~/")


来源:https://stackoverflow.com/questions/24207591/how-do-i-use-url-content-in-non-mvc-razor-webpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!