[英]How to send form to controller using ajax in asp.net core?
[英]How to get data of selected rows of table in controller using ajax in asp.net core?
我正在創建一個在線考試項目。在“從題庫添加問題”部分我有一個問題。我想將選定行中的數據發送到 controller 但我的表格代碼有點復雜。我想獲得標題問題和成績,即使這些是選擇題,我也想得到選擇和正確答案等,所以我創建了一個 ViewModel。 這是視圖模型:
public class AddQuestionViewModel
{
public int QuestionId { get; set; }
public int ExamId { get; set; }
public string UserId { get; set; }
public decimal Grade { get; set; }
public string questionTitle { get; set; }
public List<ChoiceQuestionSelection> choice { get; set; }
public List<TrueFalseQuestion> trueFalse { get; set; }
public bool IsShow { get; set; }
public bool IsSelect { get; set; }
}
這是 html:
@model IEnumerable<AddQuestionViewModel>
<form id="QuestionsForm" method="post" asp-action="CreateQuestionFromQuestionBank">
<table class="table" id="tblQuestions">
<thead>
<tr>
<th></th>
<th></th>
<th>سوال</th>
<th>نمره</th>
<th>نوع</th>
<th>دستورات</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td><input type="checkbox" /></td>
<td><input type="hidden" name="qId" asp-for="@item.QuestionId"
/>@item.QuestionId</td>
<td>
<input name="questionTitle" asp-for="@item.questionTitle" disabled
value="@item.questionTitle" />
</td>
<td>
<input name="Grade" id="Grade[@i]" asp-for="@item.Grade"
readonly="readonly" value="@item.Grade" />
</td>
@if (item.choice.Any(ch => ch.QuestionId == item.QuestionId))
{
<td>
گزینه ای
<div>
<br />
@foreach (var choice in item.choice.Where(q => q.QuestionId
== item.QuestionId))
{
<div class="form-group" name="choices">
<label class="radio-inline" style="">
<input type="radio" disabled value=""
@((choice.IsTrue) ? "checked" : "")>
<input type="text" value="@choice.Choice" asp-
for="@item.choice" readonly="readonly" />
</label>
</div>
choices++;
}
</div>
</td>
}
else if (item.trueFalse.Any(q => q.QuestionId == item.QuestionId))
{
<td>
صحیح و غلط
<div>
<br />
@foreach (var trueFalse in item.trueFalse.Where(q =>
q.QuestionId == item.QuestionId))
{
<div>
@if (trueFalse.IsTrue)
{
<div>صحیح</div>
}
else
{
<div>غلط</div>
}
</div>
}
</div>
</td>
}
else
{
<td>تشریحی</td>
}
<td></td>
</tr>
i++;
}
</tbody>
</table>
<input name="submit" type="submit" value="save" />
</form>
這是 ajax 代碼:
<script type="text/javascript">
$(':submit').click(function (event) {
event.preventDefault();
$('input:checked').each(function () {
$this = $(this);
stringresult += $this.parent().siblings('td').text();
});
var frm = $('#QuestionsForm');
$.ajax({
url: frm.attr('action'),
method: "POST",
data: stringresult.serialize(),
}).done(function (response) {
window.location.href = response.redirectToUrl;
});
});
</script>
這是選擇題 model:
public class ChoiceQuestionSelection
{
[Key]
public int ChoiceQuestionSelectionId { get; set; }
public int QuestionId { get; set; }
public string Choice { get; set; }
public bool IsTrue { get; set; }
#region relations
public Question question { get; set; }
#endregion
}
這是真假問題 model:
public class TrueFalseQuestion
{
public int TrueFalseQuestionId { get; set; }
public int QuestionId { get; set; }
public bool IsTrue { get; set; }
#region
public Question question { get; set; }
#endregion
}
這是 controller:
[HttpPost]
public IActionResult CreateQuestionFromQuestionBank(AddQuestionViewModel addQuestions)
{
//to do something
}
我搜索了很多,但找不到像我這樣的情況。 先感謝您。
您可以使用JQuery 選擇器和find 方法來查找所選行中的元素,並獲取值。 之后,您可以創建一個 JavaScript object 來存儲這些值,然后將它們發送到 controller 並執行一些操作。
請參考以下示例代碼:
Controller:
public IActionResult QuestionIndex()
{
//test data
List<AddQuestionViewModel> items = new List<AddQuestionViewModel>()
{
new AddQuestionViewModel(){
QuestionId=101,
questionTitle="What's you name?",
UserId="User A",
ExamId=1,
Grade= 2,
IsShow=true,
IsSelect=true,
choice = new List<ChoiceQuestionSelection>(){
new ChoiceQuestionSelection(){ QuestionId=101, Choice="C1", IsTrue=true, ChoiceQuestionSelectionId=1}
}
},
new AddQuestionViewModel(){
QuestionId=102,
questionTitle="How are you?",
UserId="User B",
ExamId=2,
Grade= 2,
IsShow=true,
IsSelect=true,
choice = new List<ChoiceQuestionSelection>(){
new ChoiceQuestionSelection(){ QuestionId=102, Choice="C2", IsTrue=true, ChoiceQuestionSelectionId=1}
}
}
};
return View(items);
}
//Since we might submit multiple selected items, it is better to use a List to receive the records.
[HttpPost]
public IActionResult CreateQuestionFromQuestionBank(List<AddQuestionViewModel> addQuestions)
{
//to do something
return Json(new { status = "Success", redirectToUrl = "/Reports/Index" });
}
索引視圖頁面:
@model IEnumerable<WebApplication.Models.AddQuestionViewModel>
@{
ViewData["Title"] = "QuestionIndex";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<form id="QuestionsForm" method="post" asp-action="CreateQuestionFromQuestionBank">
<table class="table" id="tblQuestions">
<thead>
<tr>
<th></th>
<th></th>
<th>سوال</th>
<th>نمره</th>
<th>نوع</th>
<th>دستورات</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td><input type="checkbox" /></td>
<td>
<input type="hidden" name="qId" asp-for="@item.QuestionId" />@item.QuestionId
</td>
<td>
<input name="questionTitle" asp-for="@item.questionTitle" disabled
value="@item.questionTitle" />
</td>
<td>
<input name="Grade" id="Grade" asp-for="@item.Grade"
readonly="readonly" value="@item.Grade" />
</td>
@if (item.choice.Any(ch => ch.QuestionId == item.QuestionId))
{
<td>
گزینه ای
<div>
<br />
@foreach (var choice in item.choice.Where(q => q.QuestionId
== item.QuestionId))
{
<div class="form-group" name="choices">
<label class="radio-inline" style="">
<input type="radio" disabled value=""
@((choice.IsTrue) ? "checked" : "")>
<input type="text" value="@choice.Choice" asp-
for="@item.choice" readonly="readonly" />
</label>
</div>
}
</div>
</td>
}
else if (item.trueFalse.Any(q => q.QuestionId == item.QuestionId))
{
<td>
صحیح و غلط
<div>
<br />
@foreach (var trueFalse in item.trueFalse.Where(q =>
q.QuestionId == item.QuestionId))
{
<div>
@if (trueFalse.IsTrue)
{
<div>صحیح</div>
}
else
{
<div>غلط</div>
}
</div>
}
</div>
</td>
}
else
{
<td>تشریحی</td>
}
<td></td>
</tr>
}
</tbody>
</table>
<input name="submit" type="submit" value="save" />
</form>
索引頁面中的腳本:
@section Scripts{
<script>
$(function () {
$(':submit').click(function (event) {
event.preventDefault();
//define an array to store the selected AddQuestionViewModel list.
var selectedModel = [];
//loop through all checked checkbox.
$("input[type='checkbox']:checked").each(function (index, item) {
//get current row
var tr = $(item).closest('tr');
//define an object to store the AddQuestionViewModel information.
var model = new Object();
//using find method to find element from current row, and then get the value.
model.questionId = $(tr).find("input[name='qId']").val();
model.questionTitle = $(tr).find("input[name='questionTitle']").val();
model.grade = $(tr).find("input[name='Grade']").val();
//define an array to store the choise list.
var choicearray = [];
//define an object to store the choise information.
var choice = new Object();
choice.IsTrue = $(tr).find("div[name='choices']").find("input:radio").is(':checked') ? true : false;
choice.choice = $(tr).find("div[name='choices']").find("input[type='text']").val();
choicearray.push(choice);
model.choice = choicearray;
//use the same method to get all the required values.
selectedModel.push(model);
});
var frm = $('#QuestionsForm');
$.ajax({
url: frm.attr('action'),
method: "POST",
data: { addQuestions: selectedModel },
}).done(function (response) {
window.location.href = response.redirectToUrl;
});
});
});
</script>
}
測試截圖如下:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.