0

I have a situation where I would like administrators to re-order questions to however they like, however, I have an issue on retrieving the value selected from the "DropDownListFor" from my form to my controller.

Placing the breakpoint at "Debug.WriteLine(MV.Count), the variable "SetNewValue" returns null in my controller

So what is the proper way to retrieve the new value that is selected and my default selected value from my DropDownListFor, as well as the current question number to my controller upon "onchange = this.form.submit()"?

I know the [HttpPost] Controller part is not a proper method to swap the questions, it is there for me to see whether the variables I have set do return the values that are sent from the DropDownListFor upon "onchange" form submit.

Any form of help is appreciated, as I am a beginner in MVC.

My View

@model IList<AppXamApplication.Models.EditQuestionsAndAnswersViewModel>

@{
ViewBag.Title = "EditQuestionsPage2";
}
<h4>Edit Your Questions Here</h4>

@using (Html.BeginForm("EditQuestionsPage2", "ExamAdmin", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
     <table id="tblQuestions" border="0" style="border:none">
     @for (int i = 0; i < Model.Count; i++)
     {
         if (Model[i].TypeOfQuestion == "Open Ended")
         {
            <tr>
                <td>
                    @Html.DropDownListFor(m => m[i].SetNewValue, new SelectList(Model[i].TotalNoQuestions, "Value", "Text", Model[i].ToSetPreSelectValue), new { @Name = "CurrentQnAction",  onchange = "this.form.submit();" })


                    @Html.HiddenFor(m => m[i].CurrentQuestionNumber, new { CurrentQnNoID = Model[i].CurrentQuestionNumber })
                </td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td>
                    @Html.ActionLink("Delete Question", "EditQuestionsPage2", new { Question_ID = Model[i].QuestionID, @class = "form-control" })
                </td>
            </tr>
            <tr>
                <td>
                    <b>Question Type: @Html.DisplayFor(m => m[i].TypeOfQuestion, new { @class = "form-control" }) </b>
                </td>
            </tr>
            <tr>
                <td>
                    @Html.EditorFor(m => m[i].QuestionsAsked, new { @class = "form-control" })
                </td>
            </tr>
            <tr>
                <td>
                    <br />
                    <br />
                </td>
            </tr>
        }
    }
</table>
}

Edited: My Model

public class EditQuestionsAndAnswersViewModel
{
    //Questions
    public string QuestionID { get; set; }
    public string TypeOfQuestion { get; set; }
    public string ExamID { get; set; }
    public string QuestionsAsked { get; set; }
    public string UserID { get; set; }
    public int? OrderingQuestions { get; set; }
    public int? CurrentQuestionNumber { get; set; }
    public string SetNewValue { get; set; }
    public int? ToSetPreSelectValue{ get; set; }
    public IList<SelectListItem> TotalNoQuestions { get; set; }
    public IList<EditAnswers> PossibleAnswers { get; set; }
    public string AnswerID { get; set; }
    public string AnswerText { get; set; }
}

Edited: My Controllers

[HttpGet]
public ActionResult EditQuestionsPage2()
{
   if (ModelState.IsValid)
   {
      using (var ctx = new AppXamApplicationEntities())
      {                   
         var CurrentExamID2 = (string)Session["CurrentExamID2"];
         string CurrentExamID2_string = Convert.ToString(CurrentExamID2);
         var query = ctx.Questions.Where(x => x.ExamID.Equals(CurrentExamID2_string))
         .Select(x => new EditQuestionsAndAnswersViewModel()
         {
                QuestionID = x.QuestionID,
                TypeOfQuestion = x.TypeOfQuestion,
                ExamID = x.ExamID,
                QuestionsAsked = x.QuestionsAsked,
                UserID = x.UserID,

                ToSetPreSelectValue= x.QuestionOrder,

                // To Order the questions in ascending order
                OrderingQuestions = x.QuestionOrder,

                // To Display Current Question Number
                CurrentQuestionNumber = x.QuestionOrder,

                // To Display the dropdownlist as well as set the default selected value to be displayed for each question in the dropdownlist
                TotalNoQuestions = ctx.Questions.Where (v=> v.ExamID.Equals(x.ExamID)).Select(v => new SelectListItem
                {
                    Value = v.QuestionOrder.ToString(),
                    Text = v.QuestionOrder.ToString(),

                 }).ToList(),
                PossibleAnswers = x.Answers.Where(y => y.QuestionID.Equals(x.QuestionID)).Select(y => new EditAnswers()
                {
                   AnswerID = y.AnswerID,
                   AnswerText = y.AnswerText
                }).ToList()
         }).ToList().AsQueryable();
            var queryOrdered = query.OrderBy(x=> x.CurrentQuestionNumber).ToList(); 
            return View(queryOrdered);
         }                
    }
    return View();
}


[HttpPost]
public ActionResult EditQuestionsPage2(string action, string CurrentQnAction, int? CurrentQnNoID, IList<EditQuestionsAndAnswersCollectionModel> MV,   string ToRetrieveSelectedValue, AddQuestions _model)
{
    if (ModelState.IsValid)
    {
        if (CurrentQnNo!= null)
        {
            //Breakpoint placed over here
            Debug.WriteLine(MV.Count);           
        }
    }
    return View();
}
  • You cannot use a `foreach` loop to generate form controls for a collection - refer [Post an HTML Table to ADO.NET DataTable](https://stackoverflow.com/questions/30094047/post-an-html-table-to-ado-net-datatable/30094943#30094943). And submitiing a form based on the change event of a ` –  Aug 30 '18 at 08:52
  • But you whole UI does not make much sense. Why not have a UI to drag and drop the items in the order you want (so a hidden input for `QuestionID` is re-ordered, and in the POST method, you will get the items back in the new order) –  Aug 30 '18 at 08:57
  • @StephenMuecke, the reason I have opted for a DropDownListFor to re-order questions is in the case where I have many questions, up to 30-40++ etc, dragging "Question 50" to "Question 1" does not seem plausible in my context. – Boby Williams Aug 30 '18 at 09:32
  • Well its a whole lot better than you current solution (even if you did fix up the multiple errors with it) –  Aug 30 '18 at 09:34
  • @StephenMuecke, I have edited the code to have an index for the collection, however my dropdownlistfor still returns null in my controller – Boby Williams Sep 03 '18 at 02:27
  • Like I said, there are **multiple** problems with your code, and another is that you have a `if` block, and if that condition is ever not met, binding will fail because you have non-consecutive indexers. And them you screw up model binding by adding `@Name = "CurrentQnAction"` (never under any circumstances do you ever attempt to change the `name` attribute when using `HtmlHelper` methods), and the list goes on and on. –  Sep 03 '18 at 02:37
  • With all due respect, stop this nonsense - you do not submit a form when an option is selected in a dropdown - you cannot even determine what the new order is unless the user changes every dropdown and ensures that every value is unique –  Sep 03 '18 at 02:40
  • @StephenMuecke, I apologise for the many errors in my code, I just started coding in MVC / web applications in general and am just learning for my project, I will look for another work-around for my intended function. Thank you for helping me! – Boby Williams Sep 03 '18 at 02:56
  • I created a DotNetFiddle for another user who had a similar issue a year or 2 ago. I will find it for you later today so you can see how to approach this –  Sep 03 '18 at 03:08
  • @StephenMuecke Appreciate the help – Boby Williams Sep 03 '18 at 03:33
  • Refer [this DotNetFiddle](https://dotnetfiddle.net/X6asp0) for a simple example. There is a lot that can be improved, but it should give you a start –  Sep 03 '18 at 03:52
  • Just hit save initially and it will show you the original order of the ID's. Then run again, and drag/drop the questions in some other order and save again to see the new order of the ID's. –  Sep 03 '18 at 03:55

0 Answers0