我有一个带有多个单选按钮的视图,这些按钮没有绑定到控制器操作方法。
视图
@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>
控制器
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();
}
}
}
我没有从视图到控制器操作方法获取所选单选按钮的列表。请帮忙。
我正在将模型对象列表传递给视图。这在单选按钮中使用,并且在按钮更改时,post方法不会获取值。
尝试将控件包装在@using(Html.BeginForm())
并且您的控制器方法应采用类型FormCollection
的参数 查看以下答案了解更多信息