I have a simple form in ASP.NET MVC. I am trying to publish these results for a controller action and I am getting weird behavior.
view is a simple HTML table:
View image http://img502.imageshack.us/img502/7271/survey.png
Here is part of the HTML form. View:
<form action="/Applications/UpdateSurvey" method="post"><table id=questionsTable class=questionsTable border=1> <thead><tr><td>Name</td><td>Answer</td><td>Name Attribute(for debugging)</td></tr> </thead><tbody> <tr> <td>Question 0:</td> <td><input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=1 >1 <input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=2 >2 <input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=3 >3 <input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=4 >4 <input type='checkbox' class='checkboxes' name='updater.questions[0].responseIds' value=5 >5 </td> <td>updater.questions[0].responseIds</td> </tr> <tr> <td>Question 1:</td> <td><input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=1 >1 <input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=2 >2 <input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=3 >3 <input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=4 >4 <input type='checkbox' class='checkboxes' name='updater.questions[1].responseIds' value=5 >5 </td> <td>updater.questions[1].responseIds</td> </tr> </tbody></table> <input type="submit" value="Save" /> </form>
Binding Object:
public class SurveyUpdater { public Question[] questions { get; set; } } public class Question { public int[] responseIds { get; set; } }
Controller Action Code:
public ActionResult UpdateSurvey(SurveyUpdater updater) { if (updater.questions == null) { //I dont understand why this is getting hit } if (updater.questions.Length != 5) { //I dont understand why this is getting hit } return View("TestSurvey"); }
After testing, here are my observations:
If I have at least one CheckBox selected for each of the questions, this also works fine in my controller updater.questions.Length == 5 , and the data is perfectly connected.
If I don’t answer one of the questions at all, I get only an array with the number that I missed: -1 . So if I did not answer question No. 3, I get the array in my control action 2.
Using logic # 2, if I don't answer the first question, I just get null for updater.questions
What I want to get (and what I expected) is the following:
I would always get questions with a length of 5 , and in cases where I did not answer one of the questions, I would just get an array of size 0 for this responseIds index.
Is this a bug in binding the ASP.NET MVC model? If not, is there something that I don’t see or in any way to get the desired behavior I'm looking for?
source share