0

I am adding checkboxes to every object in a List. When I try to return the values back to the controller the list is empty and I only get the checkbox bool.

Can someone explain to me how to pass the List correctly from the view to the controller.

I tried it with form but I am not sure if this is the correct way.

I searched a lot on Google and also found similar posts on stackoverflow but I couldn't find one that helped me.

View

@model List<WCFasp.net.WCF.Person> 
@{
    ViewBag.Title = "ShowView";
}

@using (Html.BeginForm("Check", "Home"))
{
        for (int i = 0; i < Model.Count(); i++)
        {
        <p>@Html.CheckBoxFor(m => m[i].IsChecked) @Html.DisplayFor(m => m[i].Name)</p>
        }
        <input id="submit" type="submit" value="submit" />
}

Controller

[HttpPost]
        public ActionResult Check(List<WCF.Person> selectedpersonlist)
        {
            //Here I get the empty list

            return View("ShowSelectedView");
        }

Person

[DataContract]
    public class Project
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public bool IsChecked { get; set; }

        public Project(string name, bool isChecked)
        {
            this.Name = name;
            this.IsChecked = isChecked;
        }
    }

Little question at the end. Am I getting down voted because I am not a pro or is there another reason?

3
  • Are you getting any errors? Any exceptions? One thing comes to mind is the model has a constructor which mvc does not handle well Commented Feb 8, 2016 at 10:10
  • no errors. no exceptions. Anything in my list is just empty except for the checkbox value. Commented Feb 8, 2016 at 10:21
  • So the list is not empty? It only contains the set values for IsChecked? Commented Feb 8, 2016 at 10:22

1 Answer 1

2

If you want more properties populated within your list then you can use hidden fields to store the information:

for (int i = 0; i < Model.Count(); i++)
{
    @Html.HiddenFor(m => m[i].Name)
    <p>@Html.CheckBoxFor(m => m[i].IsChecked) @Html.DisplayFor(m => m[i].Name)</p>
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.