views:

808

answers:

1

I need to make a WHERE clause for my LinqDataSource which depends on the currently logged in user. Of course, I have access to the currently logged in user in the code-behind and I specifically need the user ID to fetch only data belonging to him/her from the database.

It works fine when I add the Where attribute to the <asp:LinqDataSource /> tag but since server controls cannot have <% %> tags in them, I tried to set the Where attribute in the code-behind, in OnLoad, before data-binding the GridView which is connected to my data source.

However, when setting the attribute in the code-behind, it seems to have no effect. It works fine when I specify it manually (and statically) in the ascx code, but not from the code-behind.

I'm guessing I'm doing things in the wrong order or at the wrong times. How do I do this?

UPDATE:

Came up with this hack. I use a dummy label lblViewedUserID with Visible="false" to get a control from which I can extract the user ID. I set the text of this label from the code-behind before databinding.

I also added <WhereParameters> with a <asp:ControlParameter /> with a bunch of attributes.

<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" />

Is this really how you program ASP.NET?

A: 

The code you posted is actually a perfectly acceptable approach. If you're going to need to do this often, you can inherit from the Parameter class to make your own custom parameters. This is what we use:

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;
        }
    }
}

This works well in a number of situations - we also have a CurrentLanguageIdParameter, CurrentInstanceIdParameter, etc.

Herb Caudill