Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am working on a dynamic multiple choice form builder. In this scenario, the form can have multiple radio button list with a different question and options.
I want to get the selected options in the controller.

I tried the following code. It's not working.

What I have tried:

Model
C#
public class clsMain
    {
        public string[] selectedAnswer { get; set; }

        public List<ClsQuestions> lstQuestion { get; set; }
        public List<ClsOptions> lstOptions { get; set; }
    }

    public class ClsQuestions
    {
        public string question { get; set; }
    }

    public class ClsOptions
    {
        public int optionid { get; set; }
        public string optionvalue { get; set; }
        public string optionlable { get; set; }
    }

controller
C#
[HttpPost]
    public ActionResult FromSelectedValues(clsMain model)
    {
        return View();
    }

View
HTML
@for (int i = 0; i < 2; i++){
Question @i
 <br />
@Html.RadioButtonFor(m => m.SelectedAnswer[i], "Answer1"+i)
<label>Answer1 @i</label>
@Html.RadioButtonFor(m => m.SelectedAnswer[i], "Answer2"+i)
<label>Answer2 @i</label>
@Html.RadioButtonFor(m => m.SelectedAnswer[i], "Answer3"+i)
<label>Answer3 @i</label>
@Html.RadioButtonFor(m => m.SelectedAnswer[i], "Answer4"+i)
<label> Answer4 @i</label>
}
Posted
Updated 21-Aug-18 5:42am

1 solution

You could try doing something like this:

C#
	[HttpPost]
    public ActionResult FromSelectedValues(clsMain model)
    {
		if (ModelState.IsValid)
    	{
        	for (int i =0; i < model.lstQuestion.Count; i++)
        	{
            	var selectedAnswer = model.SelectedAnswer[i];
            	// do something here
        	}
        	
    	}
        return View();
    }
}


PS: I never tested on that, but it should help you get started on how to go through it. Also, check this article for a reference on working with Radio Buttons in MVC: Radio button list in ASP.NET MVC[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900