1

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.

2 Answers 2

2

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)

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

3 Comments

So, ActionResponse SaveAnswers(int attachmentId, FormCollection form) should give me a collection in form that contains all the key/value pairs, including attachmentId, which I already bound directly, right?
I believe that is correct. Though the id in the method signature here normally comes from the URL/routing.
Don't know if any approach is better than the other, but I ended up using this approach because it fit well with the next steps. Sure, the binder doesn't automagically prep things for me, but I needed the manual control in the following steps.
1

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.

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.