0

The following is written in ASP.NET Razor.

I have a page that dynamically creates lines in an HTML form based on results from a database query. Each row in the result set corresponds to one row in the form. Each row has two input fields that I need to be able to pass via $_POST.

foreach (var @row in list) {
    <li>
        <span style="width: 100px; display: inline-block">@row.Name</span>
        <input type="text" name="time[]" />minutes on
        <input type="text" name="date[]" />
    </li>
}

My expectation is that I would then be able to access and iterate over the data like this:

var timeList = Request.Form["time"];
foreach (var time in timeList) {
    // Stuff
}

But this isn't working. I keep getting an "Object reference not set to an instance of an object" error for timeList. Is what I'm trying to do even possible? Any idea what's wrong?

2 Answers 2

1

Try removing the square brackets from your names:

foreach (var @row in list) {
    <li>
        <span style="width: 100px; display: inline-block">@row.Name</span>
        <input type="text" name="time" />minutes on
        <input type="text" name="date" />
    </li>
}

The loop will create duplicate names which forms arrays in HTML, so you get what you want. However, I'm not sure if that will work when the list has a single item, so test that.

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

Comments

0

Client HTML:

<form action="~/Page" method="post">
    <input type="hidden" name="product_0_id" value="0" />
    <input type="text" name="product_0_name" value="Prod. #1" />
    <input type="hidden" name="product_1_id" value="1" />
    <input type="text" name="product_1_name" value="Prod. #2" />
</form>

Server:

 string youGroupKey = "product";
 Dictionary<string, string>[] values = Request.Form
     .AllKeys
     .Where(k => k.StartsWith(youGroupKey))
     .GroupBy(k => k
         .Substring(youGroupKey.Length + 1, 1),
             (a, b) => {
                 return b
                     .ToDictionary(c => c
                         .Substring(youGroupKey.Length + 3), d => Request.Form[d]);
             }
      )
      .ToArray();

Comments

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.