簡體   English   中英

服務器端ASP.net控件呈現為HTML TextArea

[英]Server-Side ASP.net controls rendered as HTML TextArea

我有一個服務器端控件,它呈現為<input type =“ Something”>或<textarea>。 該代碼是不言自明的:

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();
        }
    }

此控件旨在從數據模型獲取驗證錯誤消息(而不是向每個文本框提供“ data-val”和“ data-val-required”)。 使用此代碼很容易:

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

哪個呈現為輸入type = text標簽,而以下呈現為textarea標簽:

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

我的問題是渲染textarea時找不到任何屬性來填充textarrea的文本。 要在textarea中設置文本,我剛剛發現以下語法:

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

但是,我不知道如何在服務器控件中實現它。 我不知道自己走的路是否正確。

您需要調用普通的Write()方法在標記內寫入文本。

記住對文本進行HTML編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM