问题
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