Question

I have a form with multiple questions on it, each with their respective answers using radio buttons for the answers. In my controller, when I get the form collection, the keys hold the question id and not the selected answer id, I need the answer id to update the db correctly.

Here are my models:

public class AccreditationEditModel
{
    public int AccreditationID { get; set; }
    public int UserID { get; set; }
    public DateTime DateCompleted { get; set; }
    public List<QuestionEditModel> Questions { get; set; }
    [Display(Name = "User")]
    public string UserFullName { get; set; }

}

public class AnswerEditModel
{
    public int AnswerID { get; set; }
    public int QuestionID { get; set; }
    public string AnswerText { get; set; }
}

public class QuestionEditModel
{
    public int QuestionID { get; set; }
    public string QuestionText { get; set; }
    public List<AnswerEditModel> Answers { get; set; }
    public int AnswerID { get; set; }
}

The view:

<table>
@foreach (var Question in Model.Questions)
{ 
    <tr>
        <td colspan="2">
            <div>
                <strong>@Question.QuestionText</strong>
            </div>
        </td>
    </tr>
    foreach (var Answer in Question.Answers)
    { 
        <tr>
           <td colspan="2">
                <input style="width:10px" type="radio" id="answer_id_@Answer.AnswerID" name="Question_@Answer.QuestionID" value="@Answer.AnswerID">@Answer.AnswerText
           </td>
        </tr>
    }
}
</table>
<p>
    <input type="submit" value="Save" />
</p>

and my controller:

[HttpPost]
public ActionResult Edit(int id, FormCollection model)
{
    try
    {
        id = UserPersistance.UserId(Request);
        Accreditation a = new Accreditation();
        a.LoadByUserID(id);
        a.DateCompleted = DateTime.Now.ToUniversalTime();
        a.Save();       //Get an ID for the accreditation table for new.




        return RedirectToAction("Details");
    }
    catch
    {
        return View();
    }
}
Was it helpful?

Solution

don't use foreach. Use a for loop so you can relate it directly to your model:

for(int i=0; i< model.Questions.Count;i++)
{ 
    model.Question[i].QuestionText

    for(int j=0; j<model.Question[i].Answers.Count; j++)
    { 
        @Html.RadioButtonFor(x => x.Question[i].Answers[j], model.Questions[i].QuestionID, new { @name = model.Questions[i].QuestionID})
    }
}

OTHER TIPS

Here is the article which explains binding to complex type, i.e. class

All you need to do is provide correct name to the field that is bound to AnswerEditModel.AnswerID, e.g.: name="Answers.AnswerdID"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top