Introduction
Recently, I was tasked with interfacing with a payment gateway that required I post information via hidden input fields. I ran into problems, specifically with ASP.NET rewriting the names of my input IDs causing the gateway to ignore them. I tried several different approaches to solve this, but since I am using masterpages, nothing seemed to work.
Solution 1
My solution was to create a custom control. I included properties for “name
”, “id
”, and “value
”. Simply, all this control will do is write out “<input type="hidden" name="" id="" value="" />
” with the values for each property.
Here is the code for the control:
using System;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebCustomControls.HiddenField
{
[DefaultProperty("Value")]
[ToolboxData("<{0}:hiddenField runat="server"></{0}:hiddenField>")]
public class hiddenField : WebControl
{
[Bindable(false)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Value
{
get
{
var s = (String)ViewState["Value"];
return (s ?? String.Empty);
}
set
{
ViewState["Value"] = value;
}
}
[Bindable(false)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public override string ID
{
get
{
var s = (String)ViewState["ID"];
return (s ?? String.Empty);
}
set
{
ViewState["ID"] = value;
}
}
[Bindable(false)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Name
{
get
{
var s = (String)ViewState["Name"];
return (s ?? String.Empty);
}
set
{
ViewState["Name"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
var sb = new StringBuilder();
sb.AppendFormat(@"<input type=""hidden"" " +
@"name=""{0}"" id=""{1}"" value=""{2}"" />",
Name, ID, Value);
output.Write(sb.ToString());
}
}
}
Since I am adding these tags dynamically via code, the HTML produced by ASP.NET will look something like below. ASP.NET added the span
tags, but I can live with that.
<span id="ctl00_ctl07">
<input type="hidden" name="CID" id="CID" value="123456" />
</span>
<span id="ctl00_ctl08">
<input type="hidden" name="AMOUNT" id="AMOUNT" value="1" />
</span>
Here is some sample VB code to add an instance of the new control to your form:
Dim hidElem As New hiddenField()
hidElem.EnableViewState = False
hidElem.ID = id
hidElem.Name = id
hidElem.Value = val
Me.Form.Controls.Add(hidElem)
Solution 2
In the process of working through this, I found a better and much simpler solution. Apparently, Microsoft has already included the solution in the CLR.
Just use:
ClientScript.RegisterHiddenField("name","value")
One last thing
I also needed to post to a dynamic URL based off of a config file. I found I could set the form variables like this:
Me.Form.Method = "post"
Me.Form.Action = URL
Or even better, just include the URL in the PostBackUrl
for the Button
control.
buttonYes.PostBackUrl = URL