HtmlForm.cs source code in C# .NET

Source code for the .NET framework in C#

                        

Code:

/ DotNET / DotNET / 8.0 / untmp / whidbey / REDBITS / ndp / fx / src / xsp / System / Web / UI / HtmlForm.cs / 1 / HtmlForm.cs

                            //------------------------------------------------------------------------------ 
// 
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// 
//----------------------------------------------------------------------------- 

// HtmlForm.cs 
// 

namespace System.Web.UI.HtmlControls { 
    using System.ComponentModel;
    using System;
    using System.Collections;
    using System.Globalization; 
    using System.IO;
    using System.Text; 
    using System.Web.Configuration; 
    using System.Web.Util;
    using System.Web.UI; 
    using System.Web.UI.WebControls;
    using System.Web.Security;
    using System.Security.Permissions;
 

    ///  
    ///     
    ///       The  class defines the methods, properties, and
    ///       events for the HtmlForm control. This class provides programmatic access to the 
    ///       HTML <form> element on the server.
    ///    
    /// 
    [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] 
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
    public class HtmlForm: HtmlContainerControl 
#if ORCAS 
    , IPaginationContainer, IPaginationInfo
#endif 
    {
#if SHIPPINGADAPTERS
        private string _adaptedActionAttribute = null;
#endif 
        private string _defaultFocus;
        private string _defaultButton; 
        private bool _submitDisabledControls; 
        private const string _aspnetFormID = "aspnetForm";
 

        /// 
        /// 
        public HtmlForm() : base("form") { 
        }
 
 
        /// 
        ///     Gets or sets default button for the form 
        /// 
        [
        WebCategory("Behavior"),
        DefaultValue(""), 
        ]
        public string DefaultButton { 
            get { 
                if (_defaultButton == null) {
                    return String.Empty; 
                }
                return _defaultButton;
            }
            set { 
                _defaultButton = value;
            } 
        } 

 
        /// 
        ///     Gets or sets default focused control for the form
        /// 
        [ 
        WebCategory("Behavior"),
        DefaultValue(""), 
        ] 
        public string DefaultFocus {
            get { 
                if (_defaultFocus == null) {
                    return String.Empty;
                }
                return _defaultFocus; 
            }
            set { 
                _defaultFocus = value; 
            }
        } 

        /*
         * Encode Type property.
         */ 

        ///  
        ///     
        ///       Gets or sets the Enctype attribute of the form. This is
        ///       the encoding type that browsers 
        ///       use when posting the form's data to the server.
        ///    
        /// 
        [ 
        WebCategory("Behavior"),
        DefaultValue(""), 
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) 
        ]
        public string Enctype { 
            get {
                string s = Attributes["enctype"];
                return((s != null) ? s : String.Empty);
            } 
            set {
                Attributes["enctype"] = MapStringAttributeToString(value); 
            } 
        }
 
        /*
         * Method property.
         */
 
        /// 
        ///     
        ///       Gets or sets the Method attribute for the form. This defines how a browser 
        ///       posts form data to the server for processing. The two common methods supported
        ///       by all browsers are GET and POST. 
        ///    
        /// 
        [
        WebCategory("Behavior"), 
        DefaultValue(""),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) 
        ] 
        public string Method {
            get { 
                string s = Attributes["method"];
                return((s != null) ? s : "post");
            }
            set { 
                Attributes["method"] = MapStringAttributeToString(value);
            } 
        } 

        /* 
         * Name property.
         */

        ///  
        ///    
        ///       Gets the value of the HTML Name attribute that will be rendered to the 
        ///       browser. 
        ///    
        ///  
        [
        WebCategory("Appearance"),
        DefaultValue(""),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) 
        ]
        public virtual string Name { 
            get { 
                return UniqueID;
            } 
            set {
                // no-op setter to prevent the name from being set
            }
        } 

 
        ///  
        /// If true, forces controls disabled on the client to submit their values (thus preserving their previous postback state)
        ///  
        [
        WebCategory("Behavior"),
        DefaultValue(false)
        ] 
        public virtual bool SubmitDisabledControls {
            get { 
                return _submitDisabledControls; 
            }
            set { 
                _submitDisabledControls = value;
            }
        }
 
        /*
         * Target property. 
         */ 

        ///  
        ///    
        ///       Gets or sets the Uri of the frame or window to render the results of a Form
        ///       POST request. Developers can use this property to redirect these results to
        ///       another browser window or frame. 
        ///    
        ///  
        [ 
        WebCategory("Behavior"),
        DefaultValue(""), 
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public string Target {
            get { 
                string s = Attributes["target"];
                return((s != null) ? s : String.Empty); 
            } 

            set { 
                Attributes["target"] = MapStringAttributeToString(value);
            }
        }
 

        ///  
        /// Overridden to return a constant value or tack the ID onto the same constant value. 
        /// This fixes a bug in PocketPC which doesn't allow the name and ID of a form to be different
        ///  
        public override string UniqueID {
            get {
                if (NamingContainer == Page) {
                    return base.UniqueID; 
                }
 
                return _aspnetFormID; 
            }
        } 


        protected internal override void Render(HtmlTextWriter output) {
            Page p = Page; 
            if (p == null)
                throw new HttpException(SR.GetString(SR.Form_Needs_Page)); 
 
#pragma warning disable 0618    // To avoid deprecation warning
            if (p.SmartNavigation) { 
#pragma warning restore 0618
                ((IAttributeAccessor)this).SetAttribute("__smartNavEnabled", "true");

                // Output the IFrame 
                StringBuilder sb = new StringBuilder(""); 
                output.WriteLine(sb.ToString());
            } 

            base.Render(output);
        }
 
        private string GetActionAttribute() {
            string action; 
            VirtualPath clientFilePath = Context.Request.ClientFilePath; 

#if SHIPPINGADAPTERS 
            if (_adaptedActionAttribute != null) {
                // Action attribute set by page adapter.
                return _adaptedActionAttribute;
            } 
#endif
            // ASURT 15075/11054/59970: always set the action to the current page. 
            VirtualPath currentFilePath = Context.Request.CurrentExecutionFilePathObject; 
            if (Object.ReferenceEquals(currentFilePath, clientFilePath)) {
                // There hasn't been any Server.Transfer or RewritePath. 
                // ASURT 15979: need to use a relative path, not absolute
                action = currentFilePath.VirtualPathString;
                int iPos = action.LastIndexOf('/');
                if (iPos >= 0) { 
                    action = action.Substring(iPos+1);
                } 
            } 
            else {
                // Server.Transfer or RewritePath case.  We need to make the form action relative 
                // to the original ClientFilePath (since that's where the browser thinks we are).
                currentFilePath = clientFilePath.MakeRelative(currentFilePath);
                action = currentFilePath.VirtualPathString;
            } 

            // VSWhidbey 202380: If cookieless is on, we need to add the app path modifier to the form action 
            bool cookieless = CookielessHelperClass.UseCookieless(Context, false, FormsAuthentication.CookieMode); 
            if (cookieless && Context.Request != null && Context.Response != null) {
                action = Context.Response.ApplyAppPathModifier(action); 
            }

            // We should never return an empty action.
            Debug.Assert(!String.IsNullOrEmpty(action)); 

            string queryString = Page.ClientQueryString; 
            // ASURT 15355: Don't lose the query string if there is one. 
            // In scriptless mobile HTML, we prepend __EVENTTARGET, et. al. to the query string.  These have to be
            // removed from the form action.  Use new HttpValueCollection to leverage ToString(bool encoded). 
            if (!String.IsNullOrEmpty(queryString)) {
                action += "?" + queryString;
            }
 
            return action;
        } 
 

        ///  
        /// 
        ///     Call RegisterViewStateHandler().
        /// 
        protected internal override void OnInit(EventArgs e) { 
            base.OnInit(e);
 
            Page.SetForm(this); 

            // Make sure view state is calculated (see ASURT 73020) 
            Page.RegisterViewStateHandler();
        }

 
        /// 
        /// Overridden to handle focus stuff 
        ///  
        protected internal override void OnPreRender(EventArgs e) {
            base.OnPreRender(e); 

#pragma warning disable 0618    // To avoid deprecation warning
            if (Page.SmartNavigation) {
#pragma warning restore 0618 
                // Register the smartnav script file reference so it gets rendered
                Page.ClientScript.RegisterClientScriptResource(typeof(HtmlForm), "SmartNav.js"); 
            } 
        }
 

        /// 
        /// 
        ///  
        protected override void RenderAttributes(HtmlTextWriter writer) {
            ArrayList invalidAttributes = new ArrayList(); 
            foreach (String key in Attributes.Keys) { 
                if (!writer.IsValidFormAttribute(key)) {
                    invalidAttributes.Add(key); 
                }
            }

            foreach (String key in invalidAttributes) { 
                Attributes.Remove(key);
            } 
 
            bool enableLegacyRendering = EnableLegacyRendering;
 
            Page page = Page;
            if (writer.IsValidFormAttribute("name")) {
                // DevDiv 27328 Do not render name attribute for uplevel browser
                if (page != null && page.RequestInternal != null && 
                    (page.RequestInternal.Browser.W3CDomVersion.Major == 0 ||
                     page.XhtmlConformanceMode != XhtmlConformanceMode.Strict)) { 
                    writer.WriteAttribute("name", Name); 
                }
                Attributes.Remove("name"); 
            }

            writer.WriteAttribute("method", Method);
            Attributes.Remove("method"); 

            // Encode the action attribute - ASURT 66784 
            writer.WriteAttribute("action", GetActionAttribute(), true /*encode*/); 
            Attributes.Remove("action");
 
            // see if the page has a submit event
            if (page != null) {
                string onSubmit = page.ClientOnSubmitEvent;
                if (!String.IsNullOrEmpty(onSubmit)) { 
                    if (Attributes["onsubmit"] != null) {
                        // If there was an onsubmit on the form, register it as an onsubmit statement and remove it from the attribute collection 
                        string formOnSubmit = Attributes["onsubmit"]; 
                        if (formOnSubmit.Length > 0) {
                            if (!StringUtil.StringEndsWith(formOnSubmit, ';')) { 
                                formOnSubmit += ";";
                            }
                            if (page.ClientSupportsJavaScript || !formOnSubmit.ToLower(CultureInfo.CurrentCulture).Contains("javascript")) {
                                page.ClientScript.RegisterOnSubmitStatement(typeof(HtmlForm), "OnSubmitScript", formOnSubmit); 
                            }
                            Attributes.Remove("onsubmit"); 
                        } 
                    }
 
                    // Don't render the on submit if it contains javascript and the page doesn't support it
                    if (page.ClientSupportsJavaScript || !onSubmit.ToLower(CultureInfo.CurrentCulture).Contains("javascript")) {
                        if (enableLegacyRendering) {
                            writer.WriteAttribute("language", "javascript", false); 
                        }
                        writer.WriteAttribute("onsubmit", onSubmit); 
                    } 
                }
 
                if ((page.RequestInternal != null) &&
                    (page.RequestInternal.Browser.EcmaScriptVersion.Major > 0) &&
                    (page.RequestInternal.Browser.W3CDomVersion.Major > 0)) {
                    if (DefaultButton.Length > 0) { 
                        Control c = FindControl(DefaultButton);
 
                        // Find control from the page if it's a hierarchical ID. 
                        if (c == null && Page != null) {
                            char[] findControlSeparators = { ID_SEPARATOR, LEGACY_ID_SEPARATOR }; 
                            if (DefaultButton.IndexOfAny(findControlSeparators) != -1) {
                                c = Page.FindControl(DefaultButton);
                            }
                        } 

                        if (c is IButtonControl) { 
                            page.ClientScript.RegisterDefaultButtonScript(c, writer, false /* UseAddAttribute */); 
                        }
                        else { 
                            throw new InvalidOperationException(SR.GetString(SR.HtmlForm_OnlyIButtonControlCanBeDefaultButton, ID));
                        }
                    }
                } 
            }
 
 
            // We always want the form to have an id on the client
            // base.RenderAttributes takes care of actually rendering it. 
            EnsureID();

            base.RenderAttributes(writer);
        } 

 
        ///  
        /// 
        ///  
        protected internal override void RenderChildren(HtmlTextWriter writer) {
            // We need to register the script here since other controls might register
            // for focus during PreRender
            Page page = Page; 
            if (page != null) {
                page.OnFormRender(); 
                page.BeginFormRender(writer, UniqueID); 
            }
 
            base.RenderChildren(writer);

            if (page != null) {
                page.EndFormRender(writer, UniqueID); 
                page.OnFormPostRender();
            } 
        } 

        public override void RenderControl(HtmlTextWriter writer) { 
            if (DesignMode) {
                // User Control Designer scenario
                base.RenderChildren(writer);
            } 
            else {
                base.RenderControl(writer); 
            } 
        }
 
        protected override ControlCollection CreateControlCollection() {
            return new ControlCollection(this, 100, 2);
        }
 
#if SHIPPINGADAPTERS
        internal void RenderBeginTagInternal(HtmlTextWriter writer) { 
            RenderBeginTag(writer); 
        }
 
        internal void RenderChildrenInternal(HtmlTextWriter writer) {
            RenderChildren(writer);
        }
 
        internal void RenderEndTagInternal(HtmlTextWriter writer) {
            RenderEndTag(writer); 
        } 

        // 
        internal void SetAdaptedActionAttribute(String attr) {
            _adaptedActionAttribute = attr;
        }
#endif 

#if ORCAS 
        HttpContext _context = null; 

        int _maximumWeight = -1; 

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) 
        ]
        public int MaximumWeight { 
            get { 
                if (_maximumWeight != -1) {
                    return _maximumWeight; 
                }
                if(_context == null) {
                    _context = HttpContext.Current;
                    _maximumWeight = Int32.Parse(_context.Request.Browser["optimumPageWeight"], CultureInfo.InvariantCulture); 
                    return _maximumWeight;
                } 
                else { 
                    throw new InvalidOperationException();
                } 
            }
            set {
                _maximumWeight = value;
            } 
        }
 
 
        /// 
        bool IPaginationInfo.PaginateChildren { 
            get {
                return PaginateChildren;
            }
        } 

 
        ///  
        protected virtual bool PaginateChildren {
            get { 
                return true;
            }
        }
 

        ///  
        int IPaginationInfo.Weight { 
            get {
                return Weight; 
            }
        }

 
        /// 
        protected virtual int Weight { 
            get{ 
                return 0;
            } 
        }
#endif
    }
} 


                        

Link Menu

Network programming in C#, Network Programming in VB.NET, Network Programming in .NET
This book is available now!
Buy at Amazon US or
Buy at Amazon UK