inon
inon

Reputation: 1772

How to get the "ID" of element by the name with asp.net

I have a generic code that create a loop on the post values. and i need to get the id of the element that posted the data.

For Example, if the Html source is:

<form id="form1" runat="server">
   <input id="Name" type="text" name="Full Name" runat="server" />
   <input id="Email" type="text" name="Email Address" runat="server" />
   <input id="Phone" type="text" name="Phone Number" runat="server" />
</form>

C# code:

for (int i = 1; i < Request.Form.Count; ++i)
{
    string Value = Request.Form[i];
    if (Value != "")
    {
        string ControlName = Request.Form.Keys[i];
        string ControlId = ""; // Here I need to find the Id
    }
}

If the ControlName is: "Full Name", In ControlId I need to get: "Name" etc.

Any advice is welcome.

Upvotes: 2

Views: 6555

Answers (1)

Win
Win

Reputation: 62260

Request.Form just returns NameValueCollection.

If you want to retrieve controls inside the form as Server controls, you need to use Page.Form.

foreach (var control in Page.Form.Controls)
{
    if (control is HtmlInputControl)
    {
        var htmlInputControl = control as HtmlInputControl;
        string controlName = htmlInputControl.Name;
        string controlId = htmlInputControl.ID;
    }
}

Upvotes: 3

Related Questions