在ASP.NET MVC中,控制器中可用的Page.ResolveUrl相当于什么?
在ASP.NET MVC中,控制器中可用的Page.ResolveUrl相当于什么?
这是Url.Content:
ASPX:
<link rel="stylesheet" href="<%= Url.Content("~/Content/style.css") %>" type="text/css" />
Razor:
<link rel="stylesheet" href="@Url.Content("~/Content/style.css")" type="text/css" />
这应该是你要寻找的方法...
System.Web.VirtualPathUtility.ToAbsolute("~/")该方法可以将相对路径转换为绝对路径。
这里有很多种解析使用应用程序根运算符(~
)的路径的方法。
UrlHelper.Content
HttpServerUtility.MapPath
WebPageExecutingBase.Href
VirtualPathUtility.ToAbsolute
Control.ResolveUrl
WebViewPage
,典型的MVC页面使我们可以访问相当多的这些属性。您是否想知道当您键入@ViewData
时,您会神奇地连接到ViewData?那是因为您已经访问了MVC页面提供的属性。href="@Url.Content("~/index.html")"
href="@Server.MapPath("~/index.html")"
href="@Href("~/index.html")"
href="@VirtualPathUtility.ToAbsolute("~/index.html")"
ResolveUrl
继承的内容。如果出于某种原因,您确实想使用该特定方法,则可以新建一个控件并使用其公开的方法,但我强烈不建议这样做。@Code
Dim newControl As New System.Web.UI.Control
Dim resolvedUrl = newControl.ResolveUrl("~/index.html")
End Code
href="@resolvedUrl"
@Url.Content
,因为它最符合MVC范例。UrlHelper.Content()
和 Control.ResolveUrl()
实现的功能相同。
在Razor v2.0/ASP.NET MVC 4中,你不再需要这样做了。
只需在Razor页面中使用"~",它会自动解析路径。
<link rel="stylesheet" href="~/Content/style.css" type="text/css" />
解决此问题的另一种方法:
在页面顶部或代码后台中的代码块中解析URL。
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
Layout = "~/Pages/Shared/_IndexLayout.cshtml";
String img1 = Url.Content("~/img/people11.jpg");
}
<div class="col-12 col-lg-8" style="background-image: url('@img1');"> </div>
<script>
var isKendoWindow = false;
var myTimeOut;
clearTimeout(myTimeOut);
var sessionTimeout = (@Session.Timeout * 60000) - 5;
function doRedirect() {
if (!isKendoWindow)
window.location.href = '@Html.Raw(Href("~/Logon.aspx?brandid=" + SessionController.LandingBrandId + "&errCode=5055"))';
}
myTimeOut = setTimeout('doRedirect()', sessionTimeout);
</script>
或者您可以像这样创建自己的版本:
public static IHtmlString ResolveUrl(this HtmlHelper htmlHelper, string url)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
return htmlHelper.Raw(urlHelper.Content(url));
}
Server.MapPath() //returna full path
或者
url.content()
url.content
代替! - Paul Creasey