2010-07-20 44 views
1

我想獲得一個SelectParametersasp:SessionParameter,在會議 使用對象的屬性,而不必像Session["CustomerID"]如何在ASP中使用一個對象的屬性:SessionParameter

會話字符串像Session["Customer"]目前產權((客戶)Session["Customer"]).CustomerID)

我不知道語法要做到這一點,如果你能幫助,我會很感激

謝謝

我的代碼:

<asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="<%$ ConnectionStrings:DBConnectionString %>" xmlns:asp="#unknown"> SelectCommand="SELECT * FROM getStoreCustomers (@customerID,@week,@day)" 
ProviderName="System.Data.SqlClient"> 
<selectparameters> 
<asp:sessionparameter name="customerID" sessionfield="Customer" /> ?????? (what is the syntax to pass the property here?) 
<asp:controlparameter controlid="ddWeek" defaultvalue="-1" name="week" propertyname="SelectedValue" /> <asp:controlparameter controlid="ddDay" defaultvalue="-1" name="day" propertyname="SelectedValue" /> </selectparameters> 

我使用的類是像任何其他類(但可序列化)

[Serializable] 
public class Customer 
{ 
public int CustomerID 
{ 
get; 
set; 
} 
} 

回答

1

我明白你在說什麼,但我不認爲該參數是智能足以獲得會話中存儲的對象的屬性。我認爲這是一個基本類型,或者通過代碼使用,並明確設置默認值屬性:

ds.SelectParameters["ParamName"].DefaultValue = ((Customer)Session["Customer"]).CustomerID; 
0

你需要處理您的SqlDataSource的OnSelecting事件,並添加參數存在。

2

發現如何,從彼得。

「使用常規參數來代替,並在事件處理程序中設置的值在SqlDataSource的

<asp:Parameter Name="customerID" Type="String" /> 

的Selectingevent:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e) 
    { 
     if (Session["Customer"] != null) 
     { 
      Customer c = (Customer)Session["Customer"]; 
      e.Command.Parameters[0].Value = c.CustomerID.ToString();   
     } 

} 
0

我寫了下面的類來得到這個工作對我來說:

/// <summary> 
/// Allows to access field-values of a object in Session. 
/// </summary> 
public class SessionObjectParameter : Parameter 
{ 
    public string SessionField { get; set; } 
    public string PropertyName { get; set; } 

    protected override object Evaluate(HttpContext context, System.Web.UI.Control control) 
    { 
     if (string.IsNullOrEmpty(SessionField)) 
      throw new Exception("SessionField must be definied"); 

     if (string.IsNullOrEmpty(PropertyName)) 
      throw new Exception("PropertyName must be definied"); 

     PropertyInfo pi = context.Session[SessionField].GetType().GetProperty(this.PropertyName); 
     if (pi == null) 
      throw new Exception(string.Format("PropertyName '{0}' is not definied in the object at Session['{1}'].", this.PropertyName, this.SessionField)); 

     return pi.GetValue(context.Session[SessionField]); 
    } 
} 

有了這個,我可以使用它作爲一個簡單的SqlData參數來源:

<asp:SqlDataSource ID="dsTest" runat="server" ConnectionString='<%$ ConnectionStrings:con %>' SelectCommand="SELECT * FROM Test WHERE ([Field] = @ParValue)"> 
     <SelectParameters> 
      <costum:SessionObjectParameter Name="ParValue" SessionField="MySessionObject" PropertyName="Value" /> 
    </asp:SqlDataSource> 
相關問題