Проблема при получении значения из DropDownListFor - PullRequest
0 голосов
/ 30 августа 2018

У меня есть ситуация, когда я хотел бы, чтобы администраторы переупорядочивали вопросы так, как им нравится, однако у меня есть проблема при получении значения, выбранного из «DropDownListFor», из моей формы в мой контроллер.

Помещая точку останова в "Debug.WriteLine (MV.Count), переменная" SetNewValue "возвращает ноль в моем контроллере

Итак, как правильно выбрать новое выбранное значение и выбранное по умолчанию значение из моего DropDownListFor, а также текущий номер вопроса для моего контроллера после "onchange = this.form.submit ()"?

Я знаю, что часть контроллера [HttpPost] не является подходящим методом для обмена вопросами, я должен убедиться, что установленные мной переменные возвращают значения, отправленные из DropDownListFor при отправке формы "onchange" .

Любая форма помощи приветствуется, так как я новичок в 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>
}

Отредактировано: Моя модель

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

Отредактировано: Мои контроллеры

[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();
}
...