0

I have the following Javascript code that creates multiple textboxes depending on the number you enter.

 function generate() {
        var tot = document.getElementById("nrintrebari").value;
        var tbl = document.getElementById("sim");

        for (var i = 1; i <= tot; i++) {
            tbl.innerHTML = tbl.innerHTML + 'Intrebare nr.' + i + ' <input type="text"  size = "80" maxlength= "200" name="intrebare[]" style="height:30px; background-color:#B8B8B8; " > <br><br><br> ';
        }

    }

How can I loop through this form to get all the answers in the textboxes using C#?

3
  • Is this WebForms or MVC? Commented Feb 15, 2012 at 22:01
  • It's a simple web application... Commented Feb 15, 2012 at 22:02
  • @Rares That doesn't tell us if it is a WebForms application, or a MVC application Commented Feb 15, 2012 at 22:03

2 Answers 2

1

Regardless of Webforms or MVC, when a a form is submitted, it will contain all of the fields in the form post data.

You have chosen to dynamically inject N number of elements all with the same name, "Intrebare[]".

When you do this, the form post data will contain one element (actually a key-value pair) called "Intrebare[]", and it will contain all of the values of your dynamically injected textboxes, separated by commas.

I've put together a very small sample of code that should help you get what you need; actually my code sample iterates through the entire form post so you can see all the fields:

First, I created an empty ASP.net Web Forms Application.

<script type="text/javascript">

    function generate() {

        var tot = document.getElementById("nrintrebari").value;
        var tbl = document.getElementById("sim");

        for (var i = 1; i <= tot; i++) {
            tbl.innerHTML = tbl.innerHTML + 'Intrebare nr.' + i + ' <input type="text"  size = "80" maxlength= "200" name="intrebare[]" style="height:30px; background-color:#B8B8B8; " > <br><br><br> ';
        }

    }


</script>

<input id="nrintrebari" type="text" value="10" />

<div id="sim">
</div>

<input type="submit" value="submit" />

Result:
<asp:Label ID="TestResultLabel" runat="server" />

<script type="text/javascript">
    generate();
</script>

When the user clicks the "submit" button, the form will post with all of the dynamic textboxes included - I chose 10 for sanity...

Here is what the code looks like to go through the form collection on the code-behind:

using System;
using System.Web;
using System.Text;

namespace StackOverflow.Web.LoopThroughForm
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                GetFormElements();
            }
        }

        private void GetFormElements()
        {
            // HttpContext object contains information of the current request, 
            // and the Form object contains all of the submitted form elements
            var form = HttpContext.Current.Request.Form;
            StringBuilder sb = new StringBuilder();
            string resultFormat = "<div>Element: {0} - Value: {1}";
            for (int i = 0; i < form.Count; i++)
            {
                sb.AppendFormat(resultFormat, form.Keys[i], form[i]);
            }
            TestResultLabel.Text = sb.ToString();
        }
    }
}

This will include ALL form fields, including the ViewState field; From here you have many options, you can hardcode the "Intrebare[]" field and only get that one, and split the result by a comma:

private void GetIntrebare()
{
    var form = HttpContext.Current.Request.Form;
    StringBuilder sb = new StringBuilder();
    sb.Append("<div>Intrebare Values: <br />");
    for (int i = 0; i < form.Count; i++)
    {
        if (form.Keys[i] == "intrebare[]")
        {
            string valuesFormat = "Value {0} : {1} <br />";
            string[] values = form[i].Split(',');
            for (int ii = 0; ii < values.Length; ii++)
            { 
                // Label the value index + 1 to match the 'actual' dynamic textbox
                sb.AppendFormat(valuesFormat, ii + 1, values[ii]);
            }
        }
    }
    sb.Append("</div>");
    TestResultLabel.Text = sb.ToString();
}

I hope this helps to get you going with retrieving values form form/post data. FWIW, I believe MVC is the same - Controllers should also have the HttpContext object available that will contain all of this data, because under the hood, HTTP POST/GET does not care if you are using Java, .net, MVC, or whatever in order to read the values submitted by a user.

Sign up to request clarification or add additional context in comments.

Comments

1

when you render your input fields give a certain class to those for example question this will also give you the advantage to style all of them at once but most important you can then use JQuery to get all and only the controls with that class question assigned.

see her for the JQuery class selector example:

http://api.jquery.com/class-selector/

if you then want to get these controls server side via C# I imagine the FindControl of web forms would not work since these controls are not server controls but simple html ones. I would try to use the HTML Agility Pack to parse the page, but at postback you should make sure the controls are created again and their values are preserved.

Personally I would loop client side using the JQuery approach and send server side the values using an Ajax PageMethod or similar approach.

3 Comments

That's a great jQuery answer.. what does it have to do with c#?
ah right you wanted to loop through the controls via C#... editing
With all due respect, using HtmlAgilityPack to parse a page for post data is akin to purchasing an armored tank so you can drive to your mailbox from your driveway - complete overkill and not the right tool for this very small / simple job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.