PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlSelect.cs

https://bitbucket.org/danipen/mono
C# | 768 lines | 565 code | 130 blank | 73 comment | 136 complexity | 239f54a1b3dd345b98abc78a10cf5177 MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0
  1. //
  2. // System.Web.UI.HtmlControls.HtmlSelect.cs
  3. //
  4. // Author:
  5. // Dick Porter <dick@ximian.com>
  6. //
  7. // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System.Web.UI.WebControls;
  29. using System.Web.Util;
  30. using System.ComponentModel;
  31. using System.Collections;
  32. using System.Collections.Specialized;
  33. using System.Globalization;
  34. using System.Security.Permissions;
  35. namespace System.Web.UI.HtmlControls
  36. {
  37. // CAS
  38. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  39. [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  40. // attributes
  41. [DefaultEvent ("ServerChange")]
  42. [ValidationProperty ("Value")]
  43. [ControlBuilder (typeof (HtmlSelectBuilder))]
  44. [SupportsEventValidation]
  45. public class HtmlSelect : HtmlContainerControl, IPostBackDataHandler, IParserAccessor
  46. {
  47. static readonly object EventServerChange = new object ();
  48. DataSourceView _boundDataSourceView;
  49. bool requiresDataBinding;
  50. bool _initialized;
  51. object datasource;
  52. ListItemCollection items;
  53. public HtmlSelect () : base ("select")
  54. {
  55. }
  56. [DefaultValue ("")]
  57. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  58. [WebSysDescription("")]
  59. [WebCategory("Data")]
  60. public virtual string DataMember {
  61. get {
  62. string member = Attributes["datamember"];
  63. if (member == null) {
  64. return (String.Empty);
  65. }
  66. return (member);
  67. }
  68. set {
  69. if (value == null) {
  70. Attributes.Remove ("datamember");
  71. } else {
  72. Attributes["datamember"] = value;
  73. }
  74. }
  75. }
  76. [DefaultValue (null)]
  77. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  78. [WebSysDescription("")]
  79. [WebCategory("Data")]
  80. public virtual object DataSource {
  81. get {
  82. return (datasource);
  83. }
  84. set {
  85. if ((value != null) &&
  86. !(value is IEnumerable) &&
  87. !(value is IListSource)) {
  88. throw new ArgumentException ();
  89. }
  90. datasource = value;
  91. }
  92. }
  93. [DefaultValue ("")]
  94. public virtual string DataSourceID {
  95. get {
  96. return ViewState.GetString ("DataSourceID", "");
  97. }
  98. set {
  99. if (DataSourceID == value)
  100. return;
  101. ViewState ["DataSourceID"] = value;
  102. if (_boundDataSourceView != null)
  103. _boundDataSourceView.DataSourceViewChanged -= OnDataSourceViewChanged;
  104. _boundDataSourceView = null;
  105. OnDataPropertyChanged ();
  106. }
  107. }
  108. [DefaultValue ("")]
  109. [WebSysDescription("")]
  110. [WebCategory("Data")]
  111. public virtual string DataTextField {
  112. get {
  113. string text = Attributes["datatextfield"];
  114. if (text == null) {
  115. return (String.Empty);
  116. }
  117. return (text);
  118. }
  119. set {
  120. if (value == null) {
  121. Attributes.Remove ("datatextfield");
  122. } else {
  123. Attributes["datatextfield"] = value;
  124. }
  125. }
  126. }
  127. [DefaultValue ("")]
  128. [WebSysDescription("")]
  129. [WebCategory("Data")]
  130. public virtual string DataValueField {
  131. get {
  132. string value = Attributes["datavaluefield"];
  133. if (value == null) {
  134. return (String.Empty);
  135. }
  136. return (value);
  137. }
  138. set {
  139. if (value == null) {
  140. Attributes.Remove ("datavaluefield");
  141. } else {
  142. Attributes["datavaluefield"] = value;
  143. }
  144. }
  145. }
  146. public override string InnerHtml {
  147. get {
  148. throw new NotSupportedException ();
  149. }
  150. set {
  151. throw new NotSupportedException ();
  152. }
  153. }
  154. public override string InnerText {
  155. get {
  156. throw new NotSupportedException ();
  157. }
  158. set {
  159. throw new NotSupportedException ();
  160. }
  161. }
  162. protected bool IsBoundUsingDataSourceID {
  163. get {
  164. return (DataSourceID.Length != 0);
  165. }
  166. }
  167. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  168. [Browsable (false)]
  169. public ListItemCollection Items {
  170. get {
  171. if (items == null) {
  172. items = new ListItemCollection ();
  173. if (IsTrackingViewState)
  174. ((IStateManager) items).TrackViewState ();
  175. }
  176. return (items);
  177. }
  178. }
  179. [DefaultValue ("")]
  180. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  181. [WebSysDescription("")]
  182. [WebCategory("Behavior")]
  183. public bool Multiple {
  184. get {
  185. string multi = Attributes["multiple"];
  186. if (multi == null) {
  187. return (false);
  188. }
  189. return (true);
  190. }
  191. set {
  192. if (value == false) {
  193. Attributes.Remove ("multiple");
  194. } else {
  195. Attributes["multiple"] = "multiple";
  196. }
  197. }
  198. }
  199. [DefaultValue ("")]
  200. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  201. [WebSysDescription("")]
  202. [WebCategory("Behavior")]
  203. public string Name {
  204. get {
  205. return (UniqueID);
  206. }
  207. set {
  208. /* Do nothing */
  209. }
  210. }
  211. protected bool RequiresDataBinding {
  212. get { return requiresDataBinding; }
  213. set { requiresDataBinding = value; }
  214. }
  215. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  216. [Browsable (false)]
  217. public virtual int SelectedIndex {
  218. get {
  219. /* Make sure Items has been initialised */
  220. ListItemCollection listitems = Items;
  221. for (int i = 0; i < listitems.Count; i++) {
  222. if (listitems[i].Selected) {
  223. return (i);
  224. }
  225. }
  226. /* There is always a selected item in
  227. * non-multiple mode, if the size is
  228. * <= 1
  229. */
  230. if (!Multiple && Size <= 1) {
  231. /* Select the first item */
  232. if (listitems.Count > 0) {
  233. /* And make it stick
  234. * if there is
  235. * anything in the
  236. * list
  237. */
  238. listitems[0].Selected = true;
  239. }
  240. return (0);
  241. }
  242. return (-1);
  243. }
  244. set {
  245. ClearSelection ();
  246. if (value == -1 || items == null) {
  247. return;
  248. }
  249. if (value < 0 || value >= items.Count) {
  250. throw new ArgumentOutOfRangeException ("value");
  251. }
  252. items[value].Selected = true;
  253. }
  254. }
  255. /* "internal infrastructure" according to the docs,
  256. * but has some documentation in 2.0
  257. */
  258. protected virtual int[] SelectedIndices {
  259. get {
  260. ArrayList selected = new ArrayList ();
  261. int count = Items.Count;
  262. for (int i = 0; i < count; i++) {
  263. if (Items [i].Selected) {
  264. selected.Add (i);
  265. }
  266. }
  267. return ((int[])selected.ToArray (typeof (int)));
  268. }
  269. }
  270. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  271. public int Size {
  272. get {
  273. string size = Attributes["size"];
  274. if (size == null) {
  275. return (-1);
  276. }
  277. return (Int32.Parse (size, Helpers.InvariantCulture));
  278. }
  279. set {
  280. if (value == -1) {
  281. Attributes.Remove ("size");
  282. } else {
  283. Attributes["size"] = value.ToString ();
  284. }
  285. }
  286. }
  287. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  288. public string Value {
  289. get {
  290. int sel = SelectedIndex;
  291. if (sel >= 0 && sel < Items.Count) {
  292. return (Items[sel].Value);
  293. }
  294. return (String.Empty);
  295. }
  296. set {
  297. int sel = Items.IndexOf (value);
  298. if (sel >= 0) {
  299. SelectedIndex = sel;
  300. }
  301. }
  302. }
  303. [WebSysDescription("")]
  304. [WebCategory("Action")]
  305. public event EventHandler ServerChange {
  306. add {
  307. Events.AddHandler (EventServerChange, value);
  308. }
  309. remove {
  310. Events.RemoveHandler (EventServerChange, value);
  311. }
  312. }
  313. protected override void AddParsedSubObject (object obj)
  314. {
  315. if (!(obj is ListItem)) {
  316. throw new HttpException ("HtmlSelect can only contain ListItem");
  317. }
  318. Items.Add ((ListItem)obj);
  319. base.AddParsedSubObject (obj);
  320. }
  321. /* "internal infrastructure" according to the docs,
  322. * but has some documentation in 2.0
  323. */
  324. protected virtual void ClearSelection ()
  325. {
  326. if (items == null) {
  327. return;
  328. }
  329. int count = items.Count;
  330. for (int i = 0; i < count; i++) {
  331. items[i].Selected = false;
  332. }
  333. }
  334. protected override ControlCollection CreateControlCollection ()
  335. {
  336. return (base.CreateControlCollection ());
  337. }
  338. protected void EnsureDataBound ()
  339. {
  340. if (IsBoundUsingDataSourceID && RequiresDataBinding)
  341. DataBind ();
  342. }
  343. protected virtual IEnumerable GetData ()
  344. {
  345. if (DataSource != null && IsBoundUsingDataSourceID)
  346. throw new HttpException ("Control bound using both DataSourceID and DataSource properties.");
  347. if (DataSource != null)
  348. return DataSourceResolver.ResolveDataSource (DataSource, DataMember);
  349. if (!IsBoundUsingDataSourceID)
  350. return null;
  351. IEnumerable result = null;
  352. DataSourceView boundDataSourceView = ConnectToDataSource ();
  353. boundDataSourceView.Select (DataSourceSelectArguments.Empty, delegate (IEnumerable data) { result = data; });
  354. return result;
  355. }
  356. protected override void LoadViewState (object savedState)
  357. {
  358. object first = null;
  359. object second = null;
  360. Pair pair = savedState as Pair;
  361. if (pair != null) {
  362. first = pair.First;
  363. second = pair.Second;
  364. }
  365. base.LoadViewState (first);
  366. if (second != null) {
  367. IStateManager manager = Items as IStateManager;
  368. manager.LoadViewState (second);
  369. }
  370. }
  371. protected override void OnDataBinding (EventArgs e)
  372. {
  373. base.OnDataBinding (e);
  374. /* Make sure Items has been initialised */
  375. ListItemCollection listitems = Items;
  376. listitems.Clear ();
  377. IEnumerable list = GetData ();
  378. if (list == null)
  379. return;
  380. foreach (object container in list) {
  381. string text = null;
  382. string value = null;
  383. if (DataTextField == String.Empty &&
  384. DataValueField == String.Empty) {
  385. text = container.ToString ();
  386. value = text;
  387. } else {
  388. if (DataTextField != String.Empty) {
  389. text = DataBinder.Eval (container, DataTextField).ToString ();
  390. }
  391. if (DataValueField != String.Empty) {
  392. value = DataBinder.Eval (container, DataValueField).ToString ();
  393. } else {
  394. value = text;
  395. }
  396. if (text == null &&
  397. value != null) {
  398. text = value;
  399. }
  400. }
  401. if (text == null) {
  402. text = String.Empty;
  403. }
  404. if (value == null) {
  405. value = String.Empty;
  406. }
  407. ListItem item = new ListItem (text, value);
  408. listitems.Add (item);
  409. }
  410. RequiresDataBinding = false;
  411. IsDataBound = true;
  412. }
  413. protected virtual void OnDataPropertyChanged ()
  414. {
  415. if (_initialized)
  416. RequiresDataBinding = true;
  417. }
  418. protected virtual void OnDataSourceViewChanged (object sender,
  419. EventArgs e)
  420. {
  421. RequiresDataBinding = true;
  422. }
  423. protected internal override void OnInit (EventArgs e)
  424. {
  425. base.OnInit (e);
  426. Page.PreLoad += new EventHandler (OnPagePreLoad);
  427. }
  428. protected virtual void OnPagePreLoad (object sender, EventArgs e)
  429. {
  430. Initialize ();
  431. }
  432. protected internal override void OnLoad (EventArgs e)
  433. {
  434. if (!_initialized)
  435. Initialize ();
  436. base.OnLoad (e);
  437. }
  438. void Initialize ()
  439. {
  440. _initialized = true;
  441. if (!IsDataBound)
  442. RequiresDataBinding = true;
  443. if (IsBoundUsingDataSourceID)
  444. ConnectToDataSource ();
  445. }
  446. bool IsDataBound{
  447. get {
  448. return ViewState.GetBool ("_DataBound", false);
  449. }
  450. set {
  451. ViewState ["_DataBound"] = value;
  452. }
  453. }
  454. DataSourceView ConnectToDataSource ()
  455. {
  456. if (_boundDataSourceView != null)
  457. return _boundDataSourceView;
  458. /* verify that the data source exists and is an IDataSource */
  459. object ctrl = null;
  460. Page page = Page;
  461. if (page != null)
  462. ctrl = page.FindControl (DataSourceID);
  463. if (ctrl == null || !(ctrl is IDataSource)) {
  464. string format;
  465. if (ctrl == null)
  466. format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. A control with ID '{1}' could not be found.";
  467. else
  468. format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. '{1}' is not an IDataSource.";
  469. throw new HttpException (String.Format (format, ID, DataSourceID));
  470. }
  471. _boundDataSourceView = ((IDataSource)ctrl).GetView (String.Empty);
  472. _boundDataSourceView.DataSourceViewChanged += OnDataSourceViewChanged;
  473. return _boundDataSourceView;
  474. }
  475. protected internal override void OnPreRender (EventArgs e)
  476. {
  477. EnsureDataBound ();
  478. base.OnPreRender (e);
  479. Page page = Page;
  480. if (page != null && !Disabled) {
  481. page.RegisterRequiresPostBack (this);
  482. page.RegisterEnabledControl (this);
  483. }
  484. }
  485. protected virtual void OnServerChange (EventArgs e)
  486. {
  487. EventHandler handler = (EventHandler)Events[EventServerChange];
  488. if (handler != null) {
  489. handler (this, e);
  490. }
  491. }
  492. protected override void RenderAttributes (HtmlTextWriter w)
  493. {
  494. Page page = Page;
  495. if (page != null)
  496. page.ClientScript.RegisterForEventValidation (UniqueID);
  497. /* If there is no "name" attribute,
  498. * LoadPostData doesn't work...
  499. */
  500. w.WriteAttribute ("name", Name);
  501. Attributes.Remove ("name");
  502. /* Don't render the databinding attributes */
  503. Attributes.Remove ("datamember");
  504. Attributes.Remove ("datatextfield");
  505. Attributes.Remove ("datavaluefield");
  506. base.RenderAttributes (w);
  507. }
  508. protected internal override void RenderChildren (HtmlTextWriter w)
  509. {
  510. base.RenderChildren (w);
  511. if (items == null)
  512. return;
  513. w.WriteLine ();
  514. bool done_sel = false;
  515. int count = items.Count;
  516. for (int i = 0; i < count; i++) {
  517. ListItem item = items[i];
  518. w.Indent++;
  519. /* Write the <option> elements this
  520. * way so that the output HTML matches
  521. * the ms version (can't make
  522. * HtmlTextWriterTag.Option an inline
  523. * element, cos that breaks other
  524. * stuff.)
  525. */
  526. w.WriteBeginTag ("option");
  527. if (item.Selected && !done_sel) {
  528. w.WriteAttribute ("selected", "selected");
  529. if (!Multiple) {
  530. done_sel = true;
  531. }
  532. }
  533. w.WriteAttribute ("value", item.Value, true);
  534. if (item.HasAttributes) {
  535. AttributeCollection attrs = item.Attributes;
  536. foreach (string key in attrs.Keys)
  537. w.WriteAttribute (key, HttpUtility.HtmlAttributeEncode (attrs [key]));
  538. }
  539. w.Write (HtmlTextWriter.TagRightChar);
  540. w.Write (HttpUtility.HtmlEncode(item.Text));
  541. w.WriteEndTag ("option");
  542. w.WriteLine ();
  543. w.Indent--;
  544. }
  545. }
  546. protected override object SaveViewState ()
  547. {
  548. object first = null;
  549. object second = null;
  550. first = base.SaveViewState ();
  551. IStateManager manager = items as IStateManager;
  552. if (manager != null) {
  553. second = manager.SaveViewState ();
  554. }
  555. if (first == null && second == null)
  556. return (null);
  557. return new Pair (first, second);
  558. }
  559. /* "internal infrastructure" according to the docs,
  560. * but has some documentation in 2.0
  561. */
  562. protected virtual void Select (int[] selectedIndices)
  563. {
  564. if (items == null) {
  565. return;
  566. }
  567. ClearSelection ();
  568. int count = items.Count;
  569. foreach (int i in selectedIndices) {
  570. if (i >= 0 && i < count) {
  571. items[i].Selected = true;
  572. }
  573. }
  574. }
  575. protected override void TrackViewState ()
  576. {
  577. base.TrackViewState ();
  578. IStateManager manager = items as IStateManager;
  579. if (manager != null) {
  580. manager.TrackViewState ();
  581. }
  582. }
  583. protected virtual void RaisePostDataChangedEvent ()
  584. {
  585. OnServerChange (EventArgs.Empty);
  586. }
  587. protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
  588. {
  589. /* postCollection contains the values that are
  590. * selected
  591. */
  592. string[] values = postCollection.GetValues (postDataKey);
  593. bool changed = false;
  594. if (values != null) {
  595. if (Multiple) {
  596. /* We have a set of
  597. * selections. We can't just
  598. * set the new list, because
  599. * we need to know if the set
  600. * has changed from last time
  601. */
  602. int value_len = values.Length;
  603. int[] old_sel = SelectedIndices;
  604. int[] new_sel = new int[value_len];
  605. int old_sel_len = old_sel.Length;
  606. for (int i = 0; i < value_len; i++) {
  607. new_sel[i] = Items.IndexOf (values[i]);
  608. if (old_sel_len != value_len ||
  609. old_sel[i] != new_sel[i]) {
  610. changed = true;
  611. }
  612. }
  613. if (changed) {
  614. Select (new_sel);
  615. }
  616. } else {
  617. /* Just take the first one */
  618. int sel = Items.IndexOf (values[0]);
  619. if (sel != SelectedIndex) {
  620. SelectedIndex = sel;
  621. changed = true;
  622. }
  623. }
  624. }
  625. if (changed)
  626. ValidateEvent (postDataKey, String.Empty);
  627. return (changed);
  628. }
  629. bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
  630. {
  631. return LoadPostData (postDataKey, postCollection);
  632. }
  633. void IPostBackDataHandler.RaisePostDataChangedEvent ()
  634. {
  635. RaisePostDataChangedEvent ();
  636. }
  637. }
  638. }