locked
DropDownListFor always returns null. RRS feed

  • Question

  • User1164332849 posted

    I'm trying to post a value from a DropDownListFor. Below is my code:

    The model

      public class StudentTest
        {
            public List<SelectListItem> files { get; set; }
            public SelectListItem currentPath { get; set; }
            public string input { get; set; }
            public string correctOutput { get; set; }
            public string studentOutput { get; set; }
        }

    View:

    @using (Html.BeginForm("Test", "Development"))
    {
        @Html.DropDownListFor(model => model.currentPath, Model.files, "Select test case", new { @class = "dropdown", onchange = "this.form.submit();" })
    }
    <br />
    <br />
    <div class="CodeMirror cm-s-zenburn cm-error cm-bracket" style=";border:solid;top:200px;left:10px;width:500px">
        @Html.TextAreaFor(model=>model.input,new { id = "input"})
    </div>
    

    Controller:

    public ActionResult Test()
            {
                StudentTest st = new StudentTest();
                var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
                Instructor Instructor = (Instructor)user;
                st.files = new List<SelectListItem>();
                var files = Directory.GetFiles(Server.MapPath("~/Content/" + Instructor.UserName + "/inputs"));
                foreach (var file in files){
                    st.files.Add(new SelectListItem
                    {
                        Text = Path.GetFileName(file),
                        Value= file
                    });
                }
                return View(st);
            }
    
            [HttpPost]
            public ActionResult Test(StudentTest stu)
            {
                    //stu.currentpath is always null
                    stu.input = System.IO.File.ReadAllText(stu.currentPath.Value);
                return View("Test",stu);
            }

    But the value of "currentpath" returned is always null. What am I doing wrong?

    Sunday, April 23, 2017 12:49 PM

All replies

  • User-474980206 posted

    a dropdown list (<select>) only posts a single value. change your model to:

    public class StudentTest
        {
            public List<SelectListItem> files { get; set; }
            public string currentPath { get; set; }
            public string input { get; set; }
            public string correctOutput { get; set; }
            public string studentOutput { get; set; }
        }

    Sunday, April 23, 2017 8:11 PM