Home > DeveloperSection > Forums > Post form get null values in Model
Takeshi Okada
Takeshi Okada

Total Post:89

Points:629
Posted on    March-29-2014 6:44 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 1041  View(s)
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.



Pravesh Singh

Total Post:411

Points:2881
Posted on    March-29-2014 7:06 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick