MVC2 controller method that can accept unknown number of variables?
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.
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)
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.
public class QuestionUpdateModel{
public int attachmentID{get;set;}
public QuestionPair[] Questions{get;set;}
}
public class QuestionPair{
public int key{get;set;}
public string value{get;set;}
}
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.
精彩评论