Reputation: 627
Some background information: I have a form for creating a question and its possible answers. The Question class contains a property which is a list of answers. I have created a view model for this form. I have a "Delete selected answer" button on the form and a dropdownlist to select the answer to delete. I post back the form view model to the controler, and if the user pressed the specific button I remove this answer from the Question and return the model to the create page. This is what I put inside the controler action:
if (questionForm.DeleteSelectedAnswerButton != null)
{
questionForm.Question.PossibleAnswers.RemoveAt(questionForm.AnswerNoToDelete);
questionForm.DeleteSelectedAnswerButton = null;
questionForm.AnswerNoToDelete = 0;
return View(questionForm);
}
Now, I try to delete answer 2 out of 4, the AnswerNoToDelete is equal to 1, as I step through the code I see that the questionForm.Question.PossibleAnswers is a list that is correctly missing the second answer, but when I return to my view, the last answer is the one that is always missing (judging from the text that is in the text boxes). Any ideas why this might be happening? My view has a for loop (from zero to less than the length of possible answers) to render a textbox for each answer text.
Am I doing something fundamentally wrong by building a model this way. Would it be better if my possible answers were one level up: questionForm.PossibleAnswers?
Upvotes: 2
Views: 697
Reputation: 1038830
Try removing the value from the modelstate as well because html helpers will first use modelstate when binding and after that your view model values. And you have to do this for every value that you modify in your action:
if (questionForm.DeleteSelectedAnswerButton != null)
{
ModelState.Remove("Question.PossibleAnswers[" + questionForm.AnswerNoToDelete + "]");
questionForm.Question.PossibleAnswers.RemoveAt(questionForm.AnswerNoToDelete);
ModelState.Remove("DeleteSelectedAnswerButton");
questionForm.DeleteSelectedAnswerButton = null;
ModelState.Remove("AnswerNoToDelete");
questionForm.AnswerNoToDelete = 0;
return View(questionForm);
}
Upvotes: 1