POST FORM GET NULL VALUES IN MODEL

Takeshi Okada

Total Post:89

Points:629
Posted by  Takeshi Okada
 1441  View(s)
Ratings:
Rate this:

When I submit a form, my Courses List into my ViewModel is getting null values. This is my ViewModel:

public class CandidateViewModel
{
    public string Name { get; set; }
    public IList<CourseViewModel> Courses { get; set; }
    public CandidateViewModel()
    {
        Name ="Kiwanax";
        Courses = new List<CourseViewModel>();
        for (int count = 0; count < 5; ++count)
        {
            Courses.Add(new CourseViewModel(
                string.Format("Course_{0}", count), 5));
        }
    }
}
public class CourseViewModel
{
    public long ID {get; set; }
    public string Name{ get; set; }
    public OptionViewModel SelectedOption { get; set; }
    public IList<OptionViewModel> Options { get; set; }
    public CourseViewModel(string name, int numberOfOptions)
    {
        Name = name;
        Options = new List<OptionViewModel>();
        for (int count = 1; count <= numberOfOptions; ++count)
        {
            Options.Add(new OptionViewModel(count.ToString(),
                string.Format("Option {0}", count)));
        }
        SelectedOption = Options[0];
    }
}
public class OptionViewModel
{
    public string Value { get; set; }
    public string Description { get; set; }
}

OK. When I create DropDownLists based on my IList, it works fine.
<ul id="cursos">
@for (int count = 0; count < Model.Courses.Count; ++count)
{
    <li>
        @Html.DropDownListFor(i => i.Courses[count].SelectedOption,
            new SelectList(Model.Courses[count].Options, "Value", "Description", Model.Courses[count].SelectedOption))
                @Html.HiddenFor(i => i.Courses[count].ID)
      @Model.Courses[count].Name
            </li>
        }
        </ul>

But, when I do post from my form, I'm getting null values from that IList.

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Post form get null values in Model

    Hi Takeshi,

    You cannot bind dropdowns to complex property values:

    i => i.Courses[count].SelectedOption

    It must be bound to the corresponding primitive type that will be sent to the server:

    i => i.Courses[count].SelectedOption.Value

    Remember that in HTML the <select> element only sends the selected value as a simple string type to the server.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!