代码之家  ›  专栏  ›  技术社区  ›  C Bauer

ASP.NET-动态添加的按钮包含额外的值属性

  •  1
  • C Bauer  · 技术社区  · 15 年前

    所以,我试图动态地向一个站点添加一个按钮,让用户知道他们在向表单添加什么。但是,当它呈现一个新按钮时,它会继续将value属性提供为“”,并忽略我添加的属性。我尝试将其修复为无效,包括在添加我的版本之前删除value属性并清除所有属性。

    WebControl myControl = null;
    string[] elementInfo = elementCode.Split(new char[] { ';' });
            switch (elementID)
            {
                case 1:
                    myControl = new Button();
                    myControl.Attributes.Remove("value");
                    myControl.Attributes.Add("type","submit");
                    break;
                case 2:
                    myControl = new TextBox();
                    myControl.Attributes.Clear();
                    myControl.Attributes.Add("type", "text");
                    break;
                case 3:
                    myControl = new CheckBox();
                    myControl.Attributes.Clear();
                    myControl.Attributes.Add("type", "checkbox");
                    break;
            }
            if (myControl != null)
            {
                string[] properties;
                if (elementCode.Length > 0)
                {
                    foreach (string attr in elementInfo)
                    {
                        properties = attr.Split(new char[] { '=' });
    
                        myControl.Attributes.Add(properties[0], properties[1]);
                    }
                }
                return myControl;
            }
            else
                return null;
    

    我知道循环正在触发,第2行中返回的值是一行,“value=submit”。事实上,标记是这样出现的:

    <div id="divLastElement">
        <input type="submit" name="ctl03" value="" type="submit" value="Submit Me!" />
    </div>
    

    我确信是第一个[value='']导致它为空,但我如何重写此行为?(您可以在生成按钮的switch语句中看到,我已经尝试提前删除value键)

    3 回复  |  直到 15 年前
        1
  •  2
  •   Wim    15 年前

    最终,使用ASP.NET按钮控件,HTML值来自ASP.NET按钮上的文本属性。我猜如果没有设置,它只是呈现另一个值属性。

    尝试将按钮上的.text属性设置为“提交我!”而不是通过属性集合设置其值。

    因此,部分代码片段如下所示:

    case 1:
       myControl = new Button();
       ((Button)myControl).Text="Submit me!";
       myControl.Attributes.Add("type","submit");
       break;
        2
  •  1
  •   Phaedrus    15 年前

    尝试使用 HtmlInputButton 相反。

        3
  •  0
  •   Colin    15 年前

    您需要使用文本属性。正如您在评论中所说,您在intellisense中看不到“text”属性。这是因为在IntelliSense中,MyControl是一个WebControl(您碰巧创建了一个按钮)。WebControl是您创建的特定控件的基类,但它本身没有“文本”属性。改为使用以下内容:

    myControl = new Button();
    ((Button)myControl).Text = "submit";
    
    推荐文章