简体   繁体   中英

pass list of objects from view to controller in asp.net

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM