MVC2控制器方法可以接受未知数量的变量?
我需要使用下面发布的数据或其变体。基本上,我需要发布可变数量的键值对来表示问题 ID 和答案字符串。
如何编写 ASP.NET MVC2 控制器方法签名来接受未知数量的键值对?
attachmentId=8809&question_712=&question_713=&question_714=&question_715=&question_716=&question_717=&question_719=&question_720=&question_721=&question_722=&question_723=&question_724=&question_725=&question_726=&question_727=&question_731=&question_738=&question_739=&question_741=&question_742=&question_743=&question_744=&question_745=&question_746=&question_747=&question_748=
请注意,在此示例中,有 26 个带有空值的问题键。可能有更多或更少的键,并且它们可能有也可能没有值。我可以重新制定客户端发送数据的方式,因此,如果最好的解决方案是重新考虑发送数据的方式,我对此持开放态度。
I need to work with the below posted data, or a variant thereof. Basically, I need to post a variable number of key-value pairs that represent a question id and answer string.
How do I write an ASP.NET MVC2 controller method signature to accept an unknown number of key-value pairs?
attachmentId=8809&question_712=&question_713=&question_714=&question_715=&question_716=&question_717=&question_719=&question_720=&question_721=&question_722=&question_723=&question_724=&question_725=&question_726=&question_727=&question_731=&question_738=&question_739=&question_741=&question_742=&question_743=&question_744=&question_745=&question_746=&question_747=&question_748=
Please note that in this example, there are 26 question keys with empty values. There may be more or less keys and they may or may not have a value. I can reformulate the way the data is sent by the client, so if the best solution is to rethink the way it is sent, I'm open to that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这基本上是
FormCollection
收集的数据。默认情况下,它在自动生成的控制器中使用。即public ActionResult Edit(int id, FormCollection集合)
This is basically the data a
FormCollection
collects. It's used in the automatically generated controllers by default. i.e.public ActionResult Edit(int id, FormCollection collection)
使用数组。默认的模型绑定器可以检测数组。
model.questions[0].key model.questions[1].value 等等作为 html 标签名称,然后构建一个遵循这些约定的对象。
之后,您的控制器应该接受 QuestionUpdateModel 类型的参数。模型绑定器应该处理其余的事情。确保按顺序索引它们,以便它可以创建没有空条目的数组。
Use an array. The default modelbinder can detect arrays.
model.questions[0].key model.questions[1].value and so on for the html tag names then build an object that follows those conventions.
After that your controller should accept an argument of QuestionUpdateModel type. The modelbinder should take care of the rest. Make sure you index them sequentially so it can create the array without null entries.