Chris Miller
Chris Miller

Reputation: 763

Add new ASP.NEt server controls with jQuery?

I have a set of fields that are repeated on a form. They are simply 3 input boxes. I have a link at the bottom of the set that says "Add More." When clicked, I use .append() in jQuery to write out a new row of input fields (and name them something unique). The problem is I am adding HTML fields, not ASP.NET server controls.

How do I access these in my code behind since they are not seen on the form until runtime (that is, runtime in the browser)?

-Chris

Upvotes: 1

Views: 3143

Answers (4)

Daniel
Daniel

Reputation: 1074

Yes, you can to it!

Well, you cannot really add "server controls", but you can certainly add input boxes client side, post it and read their values server side.

Assume you add the following input client side:

<input type="text" id="textbox_id" name="textbox_name" />

The input and its value will be sent in the request to the server, so server side code to access it would be:

string value = Request.Form["textbox_name"];

Upvotes: 3

T Nguyen
T Nguyen

Reputation: 3415

As SLaks said, this is fundamentally impossible. However, one workaround would be to "compress" all your dynamic fields into one hidden field which is itself an ASP.NET control. For example, you could set a form submit handler in jQuery which would serialize your dynamic form fields into a JSON string and set your ASP.NET hidden field to that value. Obviously, your back-end would have to de-serialize it and process it accordingly, as would your front-end when you load the page.

Upvotes: 1

FishBasketGordo
FishBasketGordo

Reputation: 23142

There's a couple of ways that you could do this. I'm assuming by "3 input boxes", you mean 3 TextBox controls:

  1. Add more TextBox controls to begin with in the markup, and hide the extra ones until the user clicks "Add more". This would be suitable if there was a reasonable upper-bound to how many controls you want the user to be allowed to add.

  2. Before postback, take the values of the newly added controls, and place them in a hidden field. The server will be able to read the values from there.

  3. Communicate the values of the controls to the server via AJAX.

I'm sure that there are other ways to accomplish this as well, but I think that one of these three will work for you.

Upvotes: 0

SLaks
SLaks

Reputation: 888303

This is fundamentally impossible.

jQuery runs purely on the client, whereas ASP.Net server-side controls exist primarily on the server.

Instead, you can communicate with server-side code using jQuery by putting information in hidden fields.

Consider switching to ASP.Net MVC, which is much better at this sort of thing.

Upvotes: 5

Related Questions