0

I'm creating an online exam project.In "add questions from question bank" part I have a problem.I want to send the datas in selected rows to controller but my table codes is a little complex.I want to get the title of questions and grades and even if those are choice questions I want to get choices and correct answers and etc so I created a ViewModel. This is the 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; }
}

This is the 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>

This is the ajax code:

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

This is choice question 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
}

This is truefalse question 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
}

This is the controller:

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

I searched a lot but I couldn't find anything like my situation. Thank you in advance.

1

1 Answer 1

0

You could use JQuery Selectors and the find method to find the elements in the selected row, and get the value. After that, you could create a JavaScript object to store these values, then, send them to the controller and do something.

Please refer the following sample code:

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" });
    }

Index View page:

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

The Scripts in the Index page:

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

The test screenshot like this:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.