2017-10-08 43 views
0

我試圖動態格式化剃刀Url.Action調用下面的代碼動態格式:剃刀的Javascript錨不工作

<script> 

function getArchiveDisplayStr(str) 
{ 
    var parts = str.split("-"); 
    var year = parts[0]; 
    var month = getMonth(parts[1]); 
    return year + " " + month; 
} 

function getMonth(monthStr) 
{ 
    switch (monthStr) 
    { 
    case "1": 
     return "Jan"; 

    case "2": 
     return "Feb"; 

    case "3": 
     return "Mar"; 

    case "4": 
     return "Apr"; 

    case "5": 
     return "May"; 

    case "6": 
     return "Jun"; 

    case "7": 
     return "Jul"; 

    case "8": 
     return "Aug"; 

    case "9": 
     return "Sep"; 

    case "10": 
     return "Oct"; 

    case "11": 
     return "Nov"; 

    case "12": 
     return "Dec"; 

    default: 
     return ""; 
    } 
} 

function createAnchor(monthID) 
{ 
    var displayMonth = getArchiveDisplayStr(monthID); 
    return '<a href="@@Url.Action("GetMonth", "Blog", new {monthID="2009-10"})">2009 Sep</a>'; 
} 

</script> 

<div> 
    <script> 
     var anchor = createAnchor('2009-10'); 
     alert(anchor); 
     document.write(anchor); 
    </script> 
</div> 

當我運行這段代碼的提示框顯示:

<a href="@@Url.Action("GetMonth", "Blog", new {monthID="2009-10"})">2009 Oct</a> 

這是我所期望的。然而,當我檢查鏈接我看到以下內容:

<a href="@@Url.Action(" getmonth",="" "blog",="" new="" {monthid="2009-10" })"="">2009 Oct</a> 

我需要動態創建這些鏈接,但我不明白爲什麼鏈接被越來越設定不同於警告框。我錯過了什麼?

+0

我錯過了它,直到我剛看到答案,我沒有從createAnchor函數中移除測試。函數如下所示: 函數createAnchor(monthID) var displayMonth = getArchiveDisplayStr(monthID); return'' + displayMonth + ''; } 發佈的答案給出了我一直得到的結果,所以我不確定它是否是真正的修復。 –

回答

0
function createAnchor(monthID) 
{ 
    var Href='@(Url.Action("GetMonth", "Blog", new {monthID="2009-10"}))'; 
    var displayMonth = getArchiveDisplayStr(monthID); 
    return '<a href="'+ Href +'">2009 Sep</a>'; 
} 
0

不是試圖按照我的方式創建鏈接,而是最好讓Razor爲我做。

@foreach (var item in Model.ArchiveList) 
{ 
    <div class="site-normal no-space-after"> 
     @if (DateTimeFormatInfo.CurrentInfo != null) 
     { 
      var link = item.Substring(0, 4) + " " + DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(Convert.ToInt32(item.Substring(5, item.Length - 5))); 
      @Html.ActionLink(link, "GetMonth", new { monthID = item }) 
     } 
    </div> 
}