I am creating a simple survey system which is currently generating HTML such as this. This can of course be changed if the solution requires it.
<form id="surveyForm">
<input type="hidden" value="1" name="surveyId" />
<div class="questionContainer">
<h4>What is 2 + 2?</h4>
<div class="optionsContainer">
<div class="optionContainer">
<input id="option_1" value="1" type="radio" name="question_1" />
<label for="option_1">3</label>
</div>
<div class="optionContainer">
<input id="option_2" value="2" type="radio" name="question_1" />
<label for="option_2">4</label>
</div>
<div class="optionContainer">
<input id="option_3" value="3" type="radio" name="question_1" />
<label for="option_3">5</label>
</div>
</div>
<div class="freeTextContainer">
<h4>Comments:</h4>
<textarea id="freetext_1" name="freetext_1"></textarea>
</div>
</div>
<!-- Multiple questionContainer may follow -->
</form>
So as you can see I end up with some POST variables, namely question_1
, question_2
and so on, and freetext_1
, freetext_2
and so on. The values of the radio buttons corresponds to an option id found in the backend database.
Now I want to use jQuery or similar to post the response using Ajax to an MVC API Controller.
So question 1; How do I use jQuery to serialize these values into a JSON string which I can decode server side, and how do I specify an MVC method server side which accepts this json string?
Question 2: The solution suggested above isn't very elegant, and I would like to serialize it in a way which can be translated to a POCO object structure usable as an input parameter in the MVC API Method, such as:
public class SurveyAnswer
{
public int SurveyId { get; set; } // From a hidden field
public List<QuestionAnswer> Answers{ get; set; }
}
public class QuestionAnswer
{
public int QuestionId { get; set;}
public int OptionSelecion { get; set; }
public string FreeText { get; set; }
}
and then an MVC method such as this:
[HttpPost]
public ActionResult PostAnswer(SurveyAnswer answer)
{
...
}
How would I go about serializing the form to achive the above?