我目前在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。
答案 0 :(得分:0)
我会将id作为数据属性放在CheckboxFor
中 @Html.CheckBoxFor(
modelItem=>item.IsPartOfGame
, new {onclick = "SaveCheckBox(this)", data_itemid = item.Id}
})
然后我会将此用于您的javascript
function SaveCheckBox(checkboxInput) {
$.ajax({
type: 'GET',
url: 'Index',
data: {
idValue: checkboxInput.dataset.itemid
, newValue: checkboxInput.checked
},
dataType: 'json'
});
}