2012-07-12 78 views
1

我想要一個解決方案來實現一個屬性(或方法)來返回選定的對象。DropDownList返回一個對象,不僅是一個ID值

例子:

DropDownListUser.DataSource = UserList; 
User user = (User)DropDownListUser.SelectedObject; 

這可能嗎?

+0

儘管ASP .NET很神奇,但Web是無狀態的。您所需要的只是選定的「Value」屬性。在回發期間,您應該能夠根據該值找到對象。無論如何,這是它的目的。 – Yuck 2012-07-12 16:55:47

回答

1

網絡dropdownlistnot like該窗口形成combo將其與類綁定。它具有ListItems的集合,其具有ValueText。所以你只能從中獲取文本或數值。更多信息DropDownList

4

DropDownList在綁定過程中實際上並不存儲整個對象,只有文本和值由DataTextFieldDataValueField定義。爲了獲取選定的對象,您必須在頁面中本地存儲整個對象列表(例如ViewState)。你還必須拿出你自己的DropDownList實現來處理列表和本地存儲之間的列表。

我認爲在本地緩存列表會比較簡單(爲了節省自己的時間回到數據庫),只需使用SelectedValue進行查找即可。

0

您可以擴展DropDownList並使其保留會話中的對象列表。

像這樣:

DropDownListKeepRef:

using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
using System.Collections; 
using System.ComponentModel; 
using System.Collections.Generic; 

namespace Q11456633WebApp 
{ 
    /// <summary> 
    /// Extension of <see cref="DropDownList"/> supporting reference to the 
    /// object related to the selected line. 
    /// </summary> 
    [ValidationProperty("SelectedItem")] 
    [SupportsEventValidation] 
    [ToolboxData(
     "<{0}:DropDownListKeepRef runat=\"server\"></{0}:DropDownListKeepRef>")] 
    public class DropDownListKeepRef : DropDownList 
    { 
     protected override void PerformDataBinding(System.Collections.IEnumerable dataSource) 
     { 
      if (!String.IsNullOrEmpty(this.DataValueField)) 
      { 
       throw new InvalidOperationException(
        "'DataValueField' cant be define in this implementation. This Control use the index of list"); 
      } 

      this.Items.Clear(); 
      ArrayList list = new ArrayList(); 
      int valueInt = 0; 
      if (this.FirstNull) 
      { 
       list.Add(null); 
       this.Items.Add(new ListItem(this.FirstNullText, valueInt.ToString())); 
       valueInt++; 
      } 
      foreach (object item in dataSource) 
      { 
       String textStr = null; 
       if (item != null) 
       { 
        Object textObj = item.GetType().GetProperty(this.DataTextField).GetValue(item, null); 
        textStr = textObj != null ? textObj.ToString() : ""; 
       } 
       else 
       { 
        textStr = ""; 
       } 

       //montando a listagem 
       list.Add(item); 
       this.Items.Add(new ListItem(textStr, valueInt.ToString())); 
       valueInt++; 
      } 
      this.listOnSession = list; 
     } 

     private bool firstNull = false; 
     /// <summary> 
     /// If <c>true</ c> include a first line that will make reference to <c>null</c>, 
     /// otherwise there will be only the line from the DataSource. 
     /// </summary> 
     [DefaultValue(false)] 
     [Themeable(false)] 
     public bool FirstNull 
     { 
      get 
      { 
       return firstNull; 
      } 
      set 
      { 
       firstNull = value; 
      } 
     } 

     private string firstNullText = ""; 
     /// <summary> 
     /// Text used if you want a first-line reference to <c>null</c>. 
     /// </summary> 
     [DefaultValue("")] 
     [Themeable(false)] 
     public virtual string FirstNullText 
     { 
      get 
      { 
       return firstNullText; 
      } 
      set 
      { 
       firstNullText = value; 
      } 
     } 

     /// <summary> 
     /// List that keeps the object instances. 
     /// </summary> 
     private IList listOnSession 
     { 
      get 
      { 
       return this.listOfListsOnSession[this.UniqueID + "_listOnSession"]; 
      } 
      set 
      { 
       this.listOfListsOnSession[this.UniqueID + "_listOnSession"] = value; 
      } 
     } 

     #region to avoid memory overload 
     private string currentPage 
     { 
      get 
      { 
       return (string)HttpContext.Current.Session["DdlkrCurrentPage"]; 
      } 
      set 
      { 
       HttpContext.Current.Session["DdlkrCurrentPage"] = value; 
      } 
     } 

     /// <summary> 
     /// Every time you change page, lists for the previous page will be 
     /// discarded from memory. 
     /// </summary> 
     private IDictionary<String, IList> listOfListsOnSession 
     { 
      get 
      { 
       if (currentPage != this.Page.Request.ApplicationPath) 
       { 
        currentPage = this.Page.Request.ApplicationPath; 
        HttpContext.Current.Session["DdlkrListOfListsOnSession"] = new Dictionary<String, IList>(); 
       } 
       if (HttpContext.Current.Session["DdlkrListOfListsOnSession"] == null) 
       { 
        HttpContext.Current.Session["DdlkrListOfListsOnSession"] = new Dictionary<String, IList>(); 
       } 

       return (IDictionary<String, IList>)HttpContext.Current.Session["DdlkrListOfListsOnSession"]; 
      } 
     } 
     #endregion 

     public Object SelectedObject 
     { 
      get 
      { 
       if (this.SelectedIndex > 0 && this.listOnSession.Count > this.SelectedIndex) 
        return this.listOnSession[this.SelectedIndex]; 
       else 
        return null; 
      } 
      set 
      { 
       if (!this.listOnSession.Contains(value)) 
       { 
        throw new IndexOutOfRangeException(
         "Objeto nao contido neste 'DropDownListKeepRef': " + 
         value != null ? value.ToString() : "<null>"); 
       } 
       else 
       { 
        this.SelectedIndex = this.listOnSession.IndexOf(value); 
       } 
      } 
     } 

     /// <summary> 
     /// List of related objects. 
     /// </summary> 
     public IList Objects 
     { 
      get 
      { 
       return new ArrayList(this.listOnSession); 
      } 
     } 

     [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] 
     protected override void LoadViewState(object savedState) 
     { 
      object[] totalState = null; 
      if (savedState != null) 
      { 
       totalState = (object[])savedState; 
       if (totalState.Length != 3) 
       { 
        throw new InvalidOperationException("View State Invalida!"); 
       } 
       // Load base state. 
       int i = 0; 
       base.LoadViewState(totalState[i++]); 
       // Load extra information specific to this control. 
       this.firstNull = (bool)totalState[i++]; 
       this.firstNullText = (String)totalState[i++]; 
      } 
     } 

     [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] 
     protected override object SaveViewState() 
     { 
      object baseState = base.SaveViewState(); 
      object[] totalState = new object[3]; 
      int i = 0; 
      totalState[i++] = baseState; 
      totalState[i++] = this.firstNull; 
      totalState[i++] = this.firstNullText; 
      return totalState; 
     } 
    } 
} 

的Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Q11456633WebApp._Default" %> 

<%@ Register Assembly="Q11456633WebApp" Namespace="Q11456633WebApp" TagPrefix="cc1" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server"> 
    <title>Untitled Page</title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     <cc1:DropDownListKeepRef ID="ListofDatesDdlkr" runat="server" AutoPostBack="True" DataTextField="Date" OnSelectedIndexChanged="ListofDatesDdlkr_SelectedIndexChanged"> 
     </cc1:DropDownListKeepRef>&nbsp;</div> 
    </form> 
</body> 
</html> 

Default.aspx.cs:

using System; 
using System.Data; 
using System.Configuration; 
using System.Collections; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 

namespace Q11456633WebApp 
{ 
    public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!this.IsPostBack) 
      { 
       this.ListofDatesDdlkr.DataSource = this.ListOfDate; 
       this.ListofDatesDdlkr.DataBind(); 
      } 
     } 

     private DateTime[] ListOfDate 
     { 
      get 
      { 
       return new DateTime[] 
       { 
        new DateTime(2012, 7, 1), 
        new DateTime(2012, 7, 2), 
        new DateTime(2012, 7, 3), 
        new DateTime(2012, 7, 4), 
        new DateTime(2012, 7, 5), 
       }; 
      } 
     } 

     protected void ListofDatesDdlkr_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      this.ClientScript.RegisterStartupScript(
       this.GetType(), 
       "show_type", 
       String.Format(
        "alert('Type of SelectedObject:{0}')", 
        this 
         .ListofDatesDdlkr 
          .SelectedObject 
           .GetType() 
            .FullName), 
        true); 
     } 
    } 
} 

帶有完整示例代碼的解決方案:Q11456633WebApp.7z

+1

使用'ViewState'和'Session'進行魯莽放棄,這就是爲什麼如此多的ASP .NET應用程序性能不佳和/或具有離譜的內存需求... – Yuck 2012-07-12 17:17:24

+0

我同意。這需要一些方法來清理數據。可能是這樣的:當進入一個頁面時,清除其他頁面的列表。 – Hailton 2012-07-12 17:23:43

相關問題