Vineeth NG
Vineeth NG

Reputation: 270

How to bind multiple radio button to MVC controller

I have a view with multiple radio buttons, these are not getting bind to the controller action method.

View

@model IEnumerable<Quizz.Models.QuestionTable>
@{
    ViewBag.Title = "Index";
}
<html>
<head>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('.classname').change(function () {
                $.post("",
                    {
                        qid: $(this).attr("name"),
                        answer: $(this).val()
                    },
                    function (data, status) {
                    });
            });

            $("#viewScore").click(function () {
                $.post("/Exam/ViewScore",
                    function (data, status) {
                       // alert("Data: " + data + "\nStatus: " + status);
                        $("#result").html(data);
                    });
            });
        });

    </script>
</head>

<h2>Index</h2>
<div>

    @foreach (var item in Model)
    {
        <br />@Html.DisplayFor(x => item.question)<br />
        @Html.RadioButton(item.qid.ToString(), item.op1, false, new { @class = "classname" })@item.op1 <br />
        @Html.RadioButton(item.qid.ToString(), item.op2, false, new { @class = "classname" })@item.op2 <br />
        @Html.RadioButton(item.qid.ToString(), item.op3, false, new { @class = "classname" })@item.op3 <br />
        @Html.RadioButton(item.qid.ToString(), item.op4, false, new { @class = "classname" })@item.op4 <br />
    }

</div>
<div>
    <input type="submit" value="Check Score" id="viewScore"/>
</div>

<h2 id="result"></h2>
</html>

Controller

using Quizz.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;
using System.Data.SqlClient;

namespace Quizz.Controllers
{
    public class ExamController : Controller
    {
        public static List<QAns> answerList = new List<QAns>();
        // GET: Exam
        public ActionResult Index()
        {
            QuizzDBEntities db = new QuizzDBEntities();
            var model = db.QuestionTables.ToList();
            return View(model);
        }


        [HttpPost]
        public ActionResult Index(QAns ans)
        {
            answerList.Add(ans);
            return new EmptyResult();
        }

        [HttpPost]
        public ActionResult ViewScore()
        {
            //Check score
            int score = 0;
            foreach (QAns ans in answerList)
            {
                SqlConnection conn = new SqlConnection("data source=DESKTOP-137HJKH\\SQLEXPRESS;initial catalog=QuizzDB;integrated security=True");
                conn.Open();
                SqlCommand command = new SqlCommand("Select qid from QuestionTable where qid="+ ans.qid + " and answer='"+ ans.answer + "'", conn);           
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {

                        score++;
                    }
                }
            }       
            answerList.Clear();
            return Content("Your scorre is " + score);//new EmptyResult();
        }
    }
}

I am not getting the list of selected radio buttons from the view to the controller action method. Please help.

I am passing a list of model objects to the view. Which is used in the radio button and on change of the button the post method is not getting the values.

Upvotes: 0

Views: 343

Answers (1)

jalsh
jalsh

Reputation: 823

Try wrapping your controls in @using(Html.BeginForm()) and your controller method should take an argument of type FormCollection check the following answer for more

Upvotes: 1

Related Questions