[英]ASP.NET LinqDataSource WHERE clause
我需要為LinqDataSource
創建一個WHERE子句,該子句取決於當前登錄的用戶。 當然,我可以在后面的代碼中訪問當前登錄的用戶,並且我特別需要用戶ID才能從數據庫中僅提取屬於他/她的數據。
當我將Where
屬性添加到<asp:LinqDataSource />
標記中時,它工作正常,但由於服務器控件中不能包含<% %>
標記,因此我嘗試在代碼后面的OnLoad
數據之前設置代碼中的Where
屬性。 -綁定連接到我的數據源的GridView。
但是,在后面的代碼中設置屬性時,它似乎沒有作用。 當我在ascx
代碼中手動(和靜態)指定它(但不是從后面的代碼中)時,它可以正常工作。
我猜我是在錯誤的順序或錯誤的時間做事。 我該怎么做呢?
更新:
想到了這個hack。 我使用帶有Visible="false"
的虛擬標簽lblViewedUserID
來獲取可以從中提取用戶ID的控件。 我在數據綁定之前從代碼后面設置了此標簽的文本。
我還添加了<WhereParameters>
和<asp:ControlParameter />
並帶有一堆屬性。
<asp:LinqDataSource ID="dsLinqSource" AutoPage="true" AutoSort="true"
ContextTypeName="Ortrac.Common.Dbml.OrComDataContext"
EnableDelete="false" TableName="myTableName" EnableInsert="false"
EnableUpdate="false" runat="server" Select="new(Edited, Activity)"
Where="TheUserID.ToString().Equals(@ViewedUserID)"><%-- HACK! --%>
<WhereParameters>
<asp:ControlParameter Name="ViewedUserID" ControlID="lblViewedUserID"
Type="String" PropertyName="Text" />
</WhereParameters>
</asp:LinqDataSource>
<%-- Dummy label --%>
<asp:Label runat="server" ID="lblViewedUserID" Visible="false" />
這真的是您編程ASP.NET的方式嗎?
您發布的代碼實際上是一種完全可以接受的方法。 如果您將需要經常執行此操作,則可以從Parameter類繼承以創建自己的自定義參數。 這是我們使用的:
public class CurrentUserIdParameter : System.Web.UI.WebControls.Parameter
{
protected override int Evaluate(System.Web.HttpContext context, System.Web.UI.Control control)
{
if (Contact.Current == null) {
return -1;
}
else {
return Contact.Current.ContactID;
}
}
}
這在許多情況下都可以很好地工作-我們還具有CurrentLanguageIdParameter,CurrentInstanceIdParameter等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.