【发布时间】:2018-08-17 09:17:48
【问题描述】:
我目前在 Visual Studio 2017 中使用 Asp.net MVC。我是使用 Asp.net MVC 的新手,无法获得我需要的值。
我有一个问题表,所有问题都显示在我的视图页面上的一个表中。每个问题都有一个布尔值,在显示时显示为复选框。我目前正在尝试编写一个脚本来获取 true 或 false 的复选框值,并且在选中该复选框的位置我正在尝试获取当前行中问题的 Id。
这是我显示问题的视图。
@model IEnumerable<CapstoneApplication.Models.Question>
@{
ViewBag.Title = "Index";
}
<h2>Questions: Admin View</h2>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/SaveCheckBox.js"></script>
<p>
@Html.ActionLink("Create Question", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.IsPartOfGame)
</th>
<th>
@Html.DisplayNameFor(model => model.Category.CategoryName)
</th>
<th>
@Html.DisplayNameFor(model => model.QuestionDescription)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.CheckBoxFor(modelItem=>item.IsPartOfGame, new {onclick = "SaveCheckBox(this)" })
</td>
<td>
@Html.DisplayFor(modelItem => item.Category.CategoryName)
</td>
<td>
@Html.DisplayFor(modelItem => item.QuestionDescription)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new {id = item.Id}) |
@Html.ActionLink("Delete", "Delete", new {id = item.Id})
</td>
</tr>
}
</table>
这是我目前正在使用的脚本。
function SaveCheckBox(checkboxInput) {
$.ajax({
type: 'GET',
url: 'Index',
data: {idValue: checkboxInput.closest("tr").getAttribute("id"),
newValue: checkboxInput.checked },
dataType: 'json'
});
}
最后,这是脚本调用的方法来赋予值。
public ActionResult Index(bool? newValue, int? idValue)
{
//save to database here
var questions = db.Questions.Include(q => q.Category);
return View(questions.ToList());
}
我遇到的问题是 newValue 始终返回正确的值,即 true 或 false 但 idValue 始终为 null 它永远不会在选中的复选框的行中获取问题的 id。
【问题讨论】:
-
您的
<tr>元素没有任何id属性,因为checkboxInput.closest("tr").getAttribute("id"),返回null -
不相关,但您的
@Html.CheckBoxFor()方法正在生成重复的id属性,这是无效的html。 -
您的代码也会抛出一个错误,因为您在实际返回 html 时指定返回
json(而且您永远不会对返回的视图执行任何操作,因此不清楚您期望此代码是什么去做。
标签: javascript jquery ajax asp.net-mvc checkbox