简体   繁体   中英

asp.net textbox dynamic creation with .CssClass attribute

I am having a scenario by which I have to dynamically create the form based on the user selection. In the form, there are few textboxes which should be added at the end to the Total Textbox.

The way I am distinguishing the textboxes to be added at the end is by specifying as below..

TextBox txt1 = new TextBox();
        txt1.ID = "txt1";
        txt1.CssClass = "addToTotal";

        TextBox txt2 = new TextBox();
        txt2.ID = "txt2";
        txt2.CssClass = "addToTotal";

        TextBox txt3 = new TextBox();
        txt3.ID = "txt3";
        txt3.CssClass = "txtTotalPoints";

        PlaceHolder1.Controls.Add(txt1);
        PlaceHolder1.Controls.Add(txt2);
        PlaceHolder1.Controls.Add(txt3);

In reality, there is no css class named 'addToTotal' in the site css file . It's just used as a flag to notify me for adding at the end.

Is it a good practice to add a.CssClass even though the actual class does not exist. Are there any pitfalls in using this methodology?

I would assume that the overhead of using a CSS class which does not exist as a marker is minimal, so I wouldn't change your implementation based on that. If you're concerned about best practices - which you could rightly be, CSS classes were never intended to be used like this - you could add a data-* attribute to the input and use that instead:

txt2.Attributes["data-addToTotal"] = "true";

...then finding those elements with JQuery:

$("input[data-addToTotal='true']")

data-* attributes are part of HTML5 , but are fully backwards compatible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM