將不確(que)定(ding)變為確(que)定(ding)~Razor視圖中是否可以嵌套JS代碼
這(zhe)個問題(ti)有點意思,Razor的自動閉合性,導致JS代(dai)碼不能直接(jie)與Razor代(dai)碼混排,原來(lai)ASPX頁面中,我們到處可見這(zhe)種代(dai)碼
<%
if(Model!=null){
foreach (var item in Model.Res_ResourceProperty_Ext.GroupBy(i => i.PlatformID))
{
string vidArr="";
string vidNameArr="";
foreach (var sub in item)
{
vidArr+=sub+",";
vidNameArr+=(new Service.EEE114.Common_BasePropValueService().GetCommon_BasePropValueByID(sub.VID ?? 0)!=null?new Service.EEE114.Common_BasePropValueService().GetCommon_BasePropValueByID(sub.VID ?? 0).Name:"")+",";
}
%>
var source = html.replace(reg, function (node, key) {
return {
'Platform_SubValValue': '<%=item.Key %>',
'Platform_SubValID': 'Platform_SubVal' + '<%=item.Key %>',
'platform': '<%=((Platform)item.Key).GetDescription()%>',
'VIDValue': '<%=vidArr %>',
'VIDDisplayName': '<%=vidNameArr %>'
}[key];
});
$("#selection").append(source);
<%}
}%>
而(er)如果是Razor頁面,這種寫法(fa),顯然是行不通的(de),因(yin)為JS變量直(zhi)接(jie)混在了(le)Razor塊(kuai)中(zhong)(zhong),使得(de)系(xi)統無法(fa)辨認(ren)JS,事實上,我們在razor中(zhong)(zhong),可以加(jia)入<script>塊(kuai)
來(lai)解(jie)決這(zhe)(zhe)個問題,上面(mian)的代碼在Razor視(shi)圖中,可以類似于這(zhe)(zhe)樣
@if (Model != null) { foreach (var item in Model.WebManageRoles.GroupBy(i => i.DepartmentID)) { foreach (var sub in item) { <script type="text/javascript"> var reg = new RegExp("\\[([^\\[\\]]*?)\\]", 'igm'); //i g m是指分(fen)別用于(yu)指定區分(fen)大小寫的匹(pi)配(pei)、全局匹(pi)配(pei)和(he)多行匹(pi)配(pei)。 var html = document.getElementById("commentTemplate").innerHTML; var source = html.replace(reg, function (node, key) { return { 'Platform_SubValValue': '@item.Key', 'Platform_SubValID': 'Role' + '@item.Key', 'platform': '@item.Key', 'VIDValue': '@sub.ManageRoleID', 'VIDDisplayName': '@sub.RoleName' }[key]; }); $("#Selection").append(source); </script> } } }
這種代碼,我(wo)們感(gan)覺比ASPX里的排版更加(jia)清晰了,呵呵!
感謝Razor!