【问题标题】:How to get data of selected rows of table in controller using ajax in asp.net core?如何使用asp.net核心中的ajax获取控制器中所选表行的数据?
【发布时间】:2021-03-09 08:15:26
【问题描述】:

我正在创建一个在线考试项目。在“从题库添加问题”部分我遇到了一个问题。我想将选定行中的数据发送到控制器,但我的表格代码有点复杂。我想得到问题和成绩的标题,即使这些是选择题,我也想获得选择和正确答案等,所以我创建了一个 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>

这是选择题模型:

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
}

这是真假问题模型:

 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
}

这是控制器:

    [HttpPost]
    public IActionResult CreateQuestionFromQuestionBank(AddQuestionViewModel addQuestions)
    {
        //to do something
    }

我搜索了很多,但找不到像我这样的情况。 提前谢谢你。

【问题讨论】:

标签: jquery ajax asp.net-core


【解决方案1】:

您可以使用JQuery Selectorsfind method 来查找所选行中的元素,并获取值。之后,您可以创建一个 JavaScript 对象来存储这些值,然后将它们发送到控制器并执行一些操作。

请参考以下示例代码:

控制器:

    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>
}

测试截图如下:

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多