为外部JavaScript文件提供Razor变量

时间:2014-09-26 10:09:07

标签: javascript asp.net-mvc razor

我想在我的内容部分显示不同的图片,具体取决于一天中的小时。 if语句工作正常,它只是将变量(包含文件的URL)传递到外部javascript中,这让我烦恼。它需要是一个外部文件,因为它太大而无法将其包含在主文件中。这个javascript处理图片的usemap区域的hilighting。

这是我的SiteLayout.cshtml,它也会在以后显示内容:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta charset="utf-8" />
    <title>@Page.Title</title>
    <link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <script type="text/javascript">mapUrlElement</script> <--- tried to define the variable up front (didnt work)
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.10.3.js"></script>
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    <script src="~/Scripts/jquery.maphilight.js"></script> <--- the javascript in question
    <meta name="viewport" content="width=device-width" />
</head>

多数民众赞成的内容将被呈现

<div id="body">
        @RenderSection("featured", required: false)
        <section class="content-wrapper main-content clear-fix">
            @RenderBody()
        </section>
</div>

现在内容文件default.cshtml

@{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "XXXXXXXXXXX";

@functions{
private String mapUrl;   <--- definition so it can be accessed throughout the whole file
}

if(@DateTime.Now.Hour > 6 && @DateTime.Now.Hour <= 8){
    mapUrl = "";
}
else if (@DateTime.Now.Hour > 8 && @DateTime.Now.Hour <= 10){
    mapUrl = "~/Images/thondorfMapt.png";
}
else if (@DateTime.Now.Hour > 10 && @DateTime.Now.Hour <= 12){
    mapUrl = "~/Images/thondorf.jpg";
}    
<input hidden id="url" value="@mapUrl"/> <--- one try to pass it as a value (didnt work)
}

<script type="text/javascript">

$(function () {    <---- the function in question
    urlElement = document.getElementById("url");  <--- getting the content of the input (no effect)
    mapUrlElement = urlElement.value;

   @* window.mapUrl = "@mapUrl";      @*... wird noch getestet ...*@

    $('img[usemap]').maphilight();    <---- this is working fine without the variable URL
});
</script>

<img width="1420" class="map" src="@mapUrl" usemap="#thondorfLayout" id="thondorf" />

最后maphilight.js中的部分应该将图片显示为它创建的画布的背景

wrap = $('<div></div>').css({
            display:'block',
            background:'url("'+this.src+'")', <--- thats were the mapUrlElement should be inserted, but i have no clue HOW !? (tried several ways)
            position:'relative',
            padding:0,
            width:this.width,
            height:this.height,
            zIndex: '1'
            });

欢呼伙伴......我希望有一个解决这个特殊问题的办法;)

0 个答案:

没有答案