服務(wù)熱線
153 8323 9821
很多次,我在使用ASP.NET數(shù)據(jù)綁定控件中綁定數(shù)據(jù)時(shí) 使用if語(yǔ)句進(jìn)行邏輯判斷!但是肯定那是失敗了!沒(méi)有辦法,既然遇到了這個(gè)棘手問(wèn)題,先Google,baidu一下吧! 其他人也有此想法,雖然方案不是很好,但我還是記錄下來(lái)吧!以便以后查看。
先來(lái)說(shuō)一說(shuō):<%# Eval(“Field”)%> 吧!
我們?cè)诳丶兄苯佑?lt;%# Eval(“Field”)%>,那他應(yīng)該相當(dāng)于:<%="str”%>和<% respose.write(“str”)%> 吧!因?yàn)樵诳丶薪壎ê笏稻椭苯语@示了!相當(dāng)于輸出咯!
我曾經(jīng)多少次想這樣寫(xiě):<%# if(Eval(“Field”)=="str”){...}else{...}%> 可惜這樣他不行啊!
1.如果簡(jiǎn)單的話可以使用三元運(yùn)算符,<%# Eval(“Field”)=="str”?"somecode":"somecode"%>
但是如何if判斷后處理很復(fù)雜呢?顯然三元運(yùn)算符不是很好!那樣頁(yè)面代碼很多,我們畢竟不是在做ASP,也不好看,美工也不好寫(xiě)樣式!
2.在后臺(tái)頁(yè)面寫(xiě)邏輯代碼,返回字符串
public void Handler(string str) { if (str.Length > 5000) { Response.Write("<div title='" + str + "'>" + str.Substring(0, 1000) + "</div>"); } else { Response.Write(str); } } // or public string Handler(string str) { if (str.Length > 5000) { return "<div title='" + str + "'>" + str.Substring(0, 1000) + "</div>"; } else { return str; } }
前臺(tái)調(diào)用:
<%# Handler(Eval("Field").ToString()) %>
注意Eval還可以綁定對(duì)象.屬性 如:<%# Handler(Eval("User.Name").ToString()) %>
3.摘自網(wǎng)絡(luò)
<% int _nIndex=0; %> <!--定義一個(gè)臨時(shí)的整型變量-->
<asp:Repeater ID="_TopicRepeater" Runat="SERVER" DataSource="...">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Title") %>
<%# DataBinder.Eval(Container.DataItem, "Author") %>
<%# DataBinder.Eval(Container.DataItem, "Clicked") %>
<%# DataBinder.Eval(Container.DataItem, "ReCount") %>
<%
int nReCount=(int)(((DataView)_TopicRepeater.DataSource).Table.Rows[_nIndex++]["ReCount"]);
// 也可以分成幾句來(lái)寫(xiě)
// DataView DV=(DataView)_TopicRepeater.DataSource;
// DV.Table.Rows[_nIndex++]["ReCount"];
if(nReCount==0) { %>
----
<% } else { %>
<%# DataBinder.Eval(Container.DataItem, "LastReplyer") %>
<% } %>
</ItemTemplate>
</asp:Repeater>