Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 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 Reply

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...