Building a Simple Iframe Custom Control

October 16, 2008

no comments

Building a Simple Iframe Custom Control

In today’s post I’m going Building a Simple IFrame Custom Control
to explain how to build
a simple custom control – in my
case it’s going to be an Iframe
custom control
.

What is an Iframe?

Iframes are a web page elements that create an inline frame which contains
another document or web page. Iframes load another html document within their
<iframe> tags. I don’t recommend the use of Iframes because they are bad for
search engine optimizations but sometimes it is proper to use them.

Building a Simple Iframe Custom Control

The first thing to do before starting to build the Iframe control is to understand
what are the optional attributes that it can have. My favorite site to check such
things is W3 Schools. If you are not familiar with that site I’m very recommending to
go and check it out. Searching the site for Iframe tag returns the following link:
HTML iframe tag. In that link I collect all the Iframe optional attributes.
After knowing what are the Iframe attributes we can start building the custom control.

First Step
From File menu choose New and then choose Project.
From the Web project types choose ASP.NET Server Control to add a new ASP.NET
server control
class library.
Add New ASP.NET Server Control Project 

Second Step
Clean the class that was generated and insert the next code instead.

    [ToolboxData("<{0}:IFrame runat=server></{0}:IFrame>")]

    public class IFrame : WebControl

    {

    }

Third Step
Add the following enum above the web control definitions:

    #region Helpers

 

    public enum eScrolling

    {

        Auto = 0,

        Yes = 1,

        No = 2,

    }

 

    #endregion

That enum will help to determine the scrolling definitions for the IFrame
control
.

Forth Step
Add the following properties to the IFrame control:

        #region Properties

 

        /// <summary>

        /// Specifies how to align the iframe according

        /// to the surrounding text.         

        /// </summary>

        [Category("Appearance")]

        public HorizontalAlign Align { get; set; }

 

        /// <summary>

        /// Specifies whether or not to display a

        /// frame border

        /// </summary>

        [Category("Appearance")]

        public bool FrameBorder { get; set; }

 

        /// <summary>

        /// A URL to a long description of the

        /// frame contents

        /// </summary>

        [Category("Appearance")]

        public string LongDesc { get; set; }

 

        /// <summary>

        /// Defines the top and bottom margins of the

        /// iframe

        /// </summary>

        [Category("Appearance")]

        public int MarginHeight { get; set; }

 

        /// <summary>

        /// Defines the left and right margins of the

        /// iframe

        /// </summary>

        [Category("Appearance")]

        public int MarginWidth { get; set; }

 

        /// <summary>

        /// Define scroll bars

        /// </summary>

        [Category("Appearance")]

        public eScrolling Scrolling { get; set; }

 

        /// <summary>

        /// The URL of the document to show in the

        /// iframe

        /// </summary>

        [Editor("System.Web.UI.Design.UrlEditor, System.Design",

            typeof(UITypeEditor)),

        Bindable(true), DefaultValue(""), UrlProperty]

        public string Src { get; set; }

 

        /// <summary>

        /// Specifies a unique name of the iframe

        /// (to use in scripts)

        /// </summary>

        public string FrameName { get; set; }

 

        #endregion

These are all the IFrame optional properties that we got from W3 Schools.
Pay attention that there are some properties like width and height that
comes a long with the WebControl definitions.

Fifth Step
Add the following const variables to the IFrame control:

        #region Consts

 

        private const string FRAME_BORDER = "frameborder";

        private const string LONG_DESC = "longdesc";

        private const string MARGIN_HEIGHT = "marginheight";

        private const string MARGIN_WIDTH = "marginwidth";

        private const string SCROLLING = "scrolling";

 

        #endregion

These const will help us to write the attributes of the control.

Sixth Step
Add the Render method to write the IFrame to the page:

        #region Methods

 

        protected override void Render(HtmlTextWriter writer)

        {

            // Don’t render if no src available

            if (string.IsNullOrEmpty(Src))

            {

                return;

            }

 

            writer.WriteBeginTag(HtmlTextWriterTag.Iframe.ToString());

            RenderProperties(writer);

            writer.Write(HtmlTextWriter.TagRightChar.ToString());

            writer.WriteEndTag(HtmlTextWriterTag.Iframe.ToString());

        }

 

        private void RenderProperties(HtmlTextWriter writer)

        {

            writer.WriteAttribute(HtmlTextWriterAttribute.Id.ToString(),
               ID);

            writer.WriteAttribute(HtmlTextWriterAttribute.Src.ToString(),
               Src);

            writer.WriteAttribute(HtmlTextWriterAttribute.Align.ToString(),
               Align.ToString());

            writer.WriteAttribute(
               FRAME_BORDER, FrameBorder ? 1.ToString() : 0.ToString());

            writer.WriteAttribute(MARGIN_HEIGHT, MarginHeight.ToString());

            writer.WriteAttribute(MARGIN_WIDTH, MarginWidth.ToString());

            writer.WriteAttribute(SCROLLING, Scrolling.ToString());

            writer.WriteAttribute(
               HtmlTextWriterAttribute.Height.ToString(), Height.ToString());

            writer.WriteAttribute(
               HtmlTextWriterAttribute.Width.ToString(), Width.ToString());

 

            if (!string.IsNullOrEmpty(CssClass))

            {

                writer.WriteAttribute(
                   HtmlTextWriterAttribute.Class.ToString(), CssClass);

            }

            if (!string.IsNullOrEmpty(FrameName))

            {

                writer.WriteAttribute(
                   HtmlTextWriterAttribute.Name.ToString(),FrameName);

            }

            if (!string.IsNullOrEmpty(LongDesc))

            {

                writer.WriteAttribute(LONG_DESC, LongDesc);

            }

        }

 

        #endregion

The Render method is one of two important methods that you have to
override when building a custom control.
The second method is CreateChildControls which wasn’t implemented.
After that the control is almost ready to use.

Last Step
I added a constructor that initialize the properties for default values.
You don’t have to write it but here is the code:

        #region Ctor

 

        /// <summary>

        /// Construct a new IFrame contorl and

        /// insert default values to the IFrame

        /// </summary>

        public IFrame()

        {

            Align = HorizontalAlign.NotSet;

            FrameBorder = false;

            LongDesc = string.Empty;

            MarginHeight = 0;

            MarginWidth = 0;

            FrameName = string.Empty;

            Scrolling = eScrolling.Auto;

            Height = Unit.Percentage(100);

            Width = Unit.Percentage(100);

        }

 

        #endregion

Wrapping up 
After you added all the code this is how the IFrame control should look like:

    #region Helpers

 

    public enum eScrolling

    {

        Auto = 0,

        Yes = 1,

        No = 2,

    }

 

    #endregion

 

    #region Control

 

    [ToolboxData("<{0}:IFrame runat=server></{0}:IFrame>")]

    public class IFrame : WebControl

    {

        #region Consts

 

        private const string FRAME_BORDER = "frameborder";

        private const string LONG_DESC = "longdesc";

        private const string MARGIN_HEIGHT = "marginheight";

        private const string MARGIN_WIDTH = "marginwidth";

        private const string SCROLLING = "scrolling";

 

        #endregion

 

        #region Properties

 

        /// <summary>

        /// Specifies how to align the iframe according

        /// to the surrounding text.         

        /// </summary>

        [Category("Appearance")]

        public HorizontalAlign Align { get; set; }

 

        /// <summary>

        /// Specifies whether or not to display a

        /// frame border

        /// </summary>

        [Category("Appearance")]

        public bool FrameBorder { get; set; }

 

        /// <summary>

        /// A URL to a long description of the

        /// frame contents

        /// </summary>

        [Category("Appearance")]

        public string LongDesc { get; set; }

 

        /// <summary>

        /// Defines the top and bottom margins of the

        /// iframe

        /// </summary>

        [Category("Appearance")]

        public int MarginHeight { get; set; }

 

        /// <summary>

        /// Defines the left and right margins of the

        /// iframe

        /// </summary>

        [Category("Appearance")]

        public int MarginWidth { get; set; }

 

        /// <summary>

        /// Define scroll bars

        /// </summary>

        [Category("Appearance")]

        public eScrolling Scrolling { get; set; }

 

        /// <summary>

        /// The URL of the document to show in the

        /// iframe

        /// </summary>

        [Editor("System.Web.UI.Design.UrlEditor, System.Design",

            typeof(UITypeEditor)),

        Bindable(true), DefaultValue(""), UrlProperty]

        public string Src { get; set; }

 

        /// <summary>

        /// Specifies a unique name of the iframe

        /// (to use in scripts)

        /// </summary>

        public string FrameName { get; set; }

 

        #endregion

 

        #region Ctor

 

        /// <summary>

        /// Construct a new IFrame contorl and

        /// insert default values to the IFrame

        /// </summary>

        public IFrame()

        {

            Align = HorizontalAlign.NotSet;

            FrameBorder = false;

            LongDesc = string.Empty;

            MarginHeight = 0;

            MarginWidth = 0;

            FrameName = string.Empty;

            Scrolling = eScrolling.Auto;

            Height = Unit.Percentage(100);

            Width = Unit.Percentage(100);

        }

 

        #endregion

 

        #region Methods

 

        protected override void Render(HtmlTextWriter writer)

        {

            // Don’t render if no src available

            if (string.IsNullOrEmpty(Src))

            {

                return;

            }

 

            writer.WriteBeginTag(HtmlTextWriterTag.Iframe.ToString());

            RenderProperties(writer);

            writer.Write(HtmlTextWriter.TagRightChar.ToString());

            writer.WriteEndTag(HtmlTextWriterTag.Iframe.ToString());

        }

 

        private void RenderProperties(HtmlTextWriter writer)

        {

            writer.WriteAttribute(HtmlTextWriterAttribute.Id.ToString(), 
               ID);

            writer.WriteAttribute(HtmlTextWriterAttribute.Src.ToString(),
               Src);

            writer.WriteAttribute(HtmlTextWriterAttribute.Align.ToString(),
               Align.ToString());

            writer.WriteAttribute(
               FRAME_BORDER, FrameBorder ? 1.ToString() : 0.ToString());

            writer.WriteAttribute(MARGIN_HEIGHT, MarginHeight.ToString());

            writer.WriteAttribute(MARGIN_WIDTH, MarginWidth.ToString());

            writer.WriteAttribute(SCROLLING, Scrolling.ToString());

            writer.WriteAttribute(
               HtmlTextWriterAttribute.Height.ToString(), Height.ToString());

            writer.WriteAttribute(
               HtmlTextWriterAttribute.Width.ToString(), Width.ToString());

 

            if (!string.IsNullOrEmpty(CssClass))

            {

                writer.WriteAttribute(
                   HtmlTextWriterAttribute.Class.ToString(), CssClass);

            }

            if (!string.IsNullOrEmpty(FrameName))

            {

                writer.WriteAttribute(
                   HtmlTextWriterAttribute.Name.ToString(), FrameName);

            }

            if (!string.IsNullOrEmpty(LongDesc))

            {

                writer.WriteAttribute(LONG_DESC, LongDesc);

            }

        }

 

        #endregion

    }

 

    #endregion

Testing the New Control

After building a control you have to test it’s functionality.
I added to the solution a new web application project and added two
web forms. The first web form only write to the response “Hello”.
The second web form holds the new IFrame control with it’s Src property
directing to the first web form. This test only shows that the control is working.
You can take the control, use it and add to it functionality as you like.

Summary

Lets sum up, in the post I explained a little about Iframes and also showed
how to build an Iframe custom control from scratch. I used that control once in a
testing project that needed to show an output pdf file that it’s location was created
dynamically. It’s still being used there until today and because it’s so simple there are
no problems with it.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>