Server-Side ASP.net controls rendered as HTML TextArea

445 views Asked by At

I have a server-side control which renders as <input type="Something"> or <textarea>. The code is self-explanatory:

public string Namespace
    {
        get { return nspace; }
        set { nspace = value; }
    }
    public string Model
    {
        get { return model; }
        set { model = value; }
    }

    public string Text
    {
        get { return text; }
        set { text = value; }
    }

    public string TextMode
    {
        get { return textMode; }
        set { textMode = value; }
    }

    public string _Type
    {
        get { return type; }
        set { type = value; }
    }

    public string Property { get; set; }

    protected override void RenderContents(HtmlTextWriter output)
    {
        output.AddAttribute(HtmlTextWriterAttribute.Id, Property.ToLower());
        output.AddAttribute(HtmlTextWriterAttribute.Name, Property.ToLower());
        output.AddAttribute(HtmlTextWriterAttribute.Type, _Type);
        if(!String.IsNullOrEmpty(Text))
            output.AddAttribute(HtmlTextWriterAttribute.Value, Text);            
        Type modelType = Type.GetType(string.Format("{0}.{1}", Namespace, Model));
        PropertyInfo propInfo = modelType.GetProperty(Property);
        var attr = propInfo.GetCustomAttribute<RequiredAttribute>(false);
        if (attr != null)
        {
            output.AddAttribute("data-val", "true");
            output.AddAttribute("data-val-required", attr.ErrorMessage);
        }
        //forces styles to be added to the control
        this.AddAttributesToRender(output);
        if (!String.IsNullOrEmpty(TextMode))
        {
            output.RenderBeginTag("textarea");
            output.RenderEndTag();
        }
        else
        {
            output.RenderBeginTag("input");
            output.RenderEndTag();
        }
    }

This control is aimed at getting validation error messages from Data Model (instead of providing "data-val" and "data-val-required" to every textbox). using this code is easy:

<ServerControlTag:ControlName Property="aProp" runat="Server" Model="MyModel" ID="txtSomething" />

Which renders as a input type=text tag, and the following renders as a textarea tag:

<ServerControlTag:ControlName Property="Description" runat="Server" Model="MyModel" TextMode="MultiLine" ID="txtDescription" class="message" />

My problem is when rendering textarea I cannot find any attribute to fill the text of textarrea. To set text in a textarea I have just found the following syntax:

<textarea ... > My Text Here </textarea>

yet, I don't know how to implement it in my server control. I don't know even if I am on the right track.

1

There are 1 answers

0
SLaks On

You need to call the normal Write() method to write text inside the tag.

Remember to HTML-encode the text.