Friday, December 28, 2007

Adding Hidden Fields Programmatically With C#

Sorry it's taken so long to get another post up. The holidays, and the fact that I have a major project due tuesday, have been keeping me from my beloved blogzorz.

This is just something I ran across in my project, it stumped me for about 10 minutes, so I did a search for it, and nothing I saw explained it adequately, or even loaded properly. So here's what I came up with.

I need to add several hidden fields to a form, that contain data needed on the receiving end of a POST request I'll be sending. The values are not static, and need to be a) pulled from a database, and b) used in a crypto method, so obviously just posting HTML input tags just wouldn't cut it. So, I tried having the input tags, but couldn't access them from the codebehind. There are two easy ways to fix this.

1) The CodeBehind Way

In the codebehind, create a new HiddenField:

Hiddenfield field = new HiddenField();

Give it a value:

field.Value = value;

...and set it's ID

field.ID = idValue;

Then, all you have to do is add it to your form:

form.Controls.Add(field);

And it's there! One interesting thing to note, though, is that the ID value you give the HiddenField will be used in the HTML as both the id attribute, and the name attribute. So, if the name attribute is important to your reciever's code (which it is in my case,) make sure you set the ID properly.

2) The Even Easier HTML Way

Add runat="server" to the input tag. I had a face-palm moment when I realized this would work, but it does. The caveat with this method, though, is you have to give it an id attribute as well, or else you won't be able to access it from the codebehind. To set the value using this method, make sure that the HTML is like so:



Then you can edit it in the codebehind as such:

nametocodebehind.Value = hiddenvalue;

And that's it! To make up for not posting last week, I'll be posting again this week, most likely about jewelry and user experience.

No comments: