Thursday, June 9, 2011

Setting the Name attribute in HtmlInputHidden fields

I was recently creating a Web Form that was using a Submit button with the PostBackUrl attribute configured to a 3rd party payment gateway (in this case, I was using Authorize.Net).

As you may or may not know, when you configure the PostBackUrl to an external website such as a 3rd party payment gateway, there is really no opportunity to perform any server side processing prior to submitting the form.

Fortunately, I found a reference to this article in the ASP.Net Forums which provides a workaround specifically for such a scenario: http://www.jigar.net/articles/viewhtmlcontent78.aspx

So after compiling a class to handle the RemotePost, I wanted to add my necessary hidden fields for submission to the Payment Gateway.

I first tried simply adding the Html Input Hidden Fields that were already present in the form.  Unfortunately, this did not work at all since the names for the hidden fields are altered by ASP.Net into a convoluted string which seems to indicate the hierarchy of the control in relation to other controls on the form.

Given this, it immediately became obvious that I would have to parse out the actual names and then assign the correct names.

Unfortunately, simply by using the following code:


HtmlInputHidden authNetHdnControl = new HtmlInputHidden();
                    authNetHdnControl.Name = strHdnControlName;
                    authNetHdnControl.Value = hdnControl.Value;

I could not get the code to work!  Each time I attempted to set the Name attribute on the HtmlInputHidden control, the Name would come back as null (even though the attribute provides a getter and setter).

Based on a hunch, I simply set the ID for the control instead, rather than attempting to set the Name attribute explicitly:



HtmlInputHidden authNetHdnControl = new HtmlInputHidden();
                    authNetHdnControl.ID = strHdnControlName;
                    authNetHdnControl.Value = hdnControl.Value;

Voila!  Everything worked properly and the Name attribute was being set based on the value I set for the ID attribute.

So, if you run into this problem yourself, just remember to set the ID attribute just like you would for a standard ASP.Net Server Control (even though the control is an Html Server Control)!




No comments:

Post a Comment