2015-05-24 63 views
0
@foreach (var item in Model.policydata) 
{ 

<tr align="center"> 
<td> 
@Html.DisplayFor(modelitem => item.Name) 
</td> 
<td> 
@Html.DisplayFor(modelitem => item.PolicyID) 
</td> 
<td> 
@Html.DisplayFor(modelitem => item.CustomerID) 
</td> 
<td>    
<a onclick="OpenRepositoryFile()" href="@string.Format("http://repository.website.com/{0}/{1}.pdf", Model.PolicyName, item.CustomerID)">View</a>  
</td> 
</tr> 
} 


</table> 
<script> 

    function OpenRepositoryFile() 
    { 

     var win = window.open('', '_blank'); 
     if(win) 
     { 
      //Browser has allowed it to be opened 
      win.focus(); 
     }else{ 
      //Broswer has blocked it 
      alert('This application feature requires Popups Enabled. Please right click to open in a new Tab or change your Browser settings'); 
     } 
    } 
</script> 

我已獲得此剃刀代碼和此Javascript函數。基本上,Razor鏈接是根據從模型變量中檢索的數據構建的,Javascript功能打開一個新的窗口/選項卡(取決於設置),或者在瀏覽器設置不允許彈出窗口時提醒用戶。單獨使用時,兩者都可以正常工作。在Javascript函數中包含剃刀格式的字符串

繼承人的問題。我希望Razor建立的鏈接作爲Javascript函數的window.open命令中的一個參數。

我想象,在Javascript或JQuery的,會有的String.Format()函數,因爲在淨的,但現在,沒有..

是否存在的一種方式獲取Razor在其標識中通過其ID生成的Href字符串屬性?或有關於此的任何其他建議?

感謝

回答

2

你可以用jQuery做到這一點很容易,只有你需要通過jQuery綁定一個帶有這個錨標籤的事件,就像下面這樣:

HTML

<a id="ancWindow" 
    href="@string.Format("http://repository.website.com/{0}/{1}.pdf", Model.PolicyName, item.CustomerID)">View</a> 

jQuery的

$(document).ready(function() { 
    $('#ancWindow').click(function(e) { 
     e.preventDefault(); // <- used to prevent redirection from anchor 
     var win = window.open(this.href, '_blank'); 
     if(win) { 
      //Browser has allowed it to be opened 
      win.focus(); 
     } else{ 
      //Broswer has blocked it 
      alert('This application feature requires Popups Enabled. Please right click to open in a new Tab or change your Browser settings'); 
     } 
    }); 
}); 

注:請確保您有jQuery的文件的參考。

+0

輝煌的代碼。看着jquery,但我的代碼知識缺乏這個部門,確實需要改進......但是有一個問題。該功能可以正常工作並打開,但即使該選項卡打開,警報也會彈出。這與瀏覽器設置有關嗎?或者可以對代碼做進一步的工作?非常感謝迄今爲止... –

0

據我瞭解的hrefonclick在一起是不兼容的,因爲它們都做同樣的事情。

要創建參數把它看成是一個字符串

@{ 
    String tempString = string.Format("http://repository.website.com/{0}/{1}.pdf", Model.PolicyName, item.CustomerID)" 
} 

然後你的電話就變成了:

OpenRepositoryFile(@(tempString)) 

警告 - 沒有測試