Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

asp.net mvc - Submitting form elements with the same name

I have a form which allows the user to create extra "rows" using JQuery (using .clone) so that they can decide how many of the same information they need to submit. My issue is that I cannot work out how to access these form items within my controller.

the form that is being submitted may look like this

<input type="text" name="Amount" id="Amount">
   <select name="Item">
       <option value="1">Item 1"</option>
       <option value="2">Item 2"</option>
       <option value="3">Item 3"</option>
   </select>
<input type="text" name="Amount" id="Amount">
   <select name="Item">
       <option value="1">Item 1"</option>
       <option value="2">Item 2"</option>
       <option value="3">Item 3"</option>
   </select>
<input type="text" name="Amount" id="Amount">
   <select name="Item">
       <option value="1">Item 1"</option>
       <option value="2">Item 2"</option>
       <option value="3">Item 3"</option>
   </select>

Basically, the block between input and the select could be repeated an infinite number of times. When I submit to the controller I am then using FormCollection form to access the form elements. from there I am unsure how I can access the items that have been submitted. I thought of using a for loop and then accessing them via something like form["Amount"][i] but obviously that is not going to work.

Am I going about this the right way and if so, does anyone have any suggestions about how this might work?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Old question, but still... You can get the posted values as an array by calling Request.Form.GetValues, or Request.QueryString.GetValues. For example:

string[] amounts = Request.Form.GetValues("Amount");

And the amounts array will contain the correct values, so you can post values containing comas, dots, whatever, and don't worry about splitting/parsing it.

Of course if you are running MVC, use the modelbinder to do it. But you can use this if you are using webforms, a generic handler, etc...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...