0

I'm trying to pass a list of items that have their checkbox checked. The problem is that when I press submit, my controller does not receive anything from the view ( my items of type IEnumerable are null )

Here is my view :

@model  IEnumerable<MyApp.Models.MyClass>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />        
</head>
<body>
    <div>       
        @using (Html.BeginForm())
        {    
            foreach(var item in Model)
            {
                Html.CheckBoxFor(modelItem => item.Checked);
                Html.DisplayFor(modelItem => item.Url);
                <br/>  
            }    

            <input type="submit" value="Submit" />
        }
    </div>
</body>
</html>

This my model :

namespace MyApp.Models
{
    public class MyClass
    {
        public string Url;
        public bool Checked;
        public MyClass(string item)
        {
            Url = item;
        }
        public MyClass()
        {

        }
    }
}

And this is my controller :

[HttpPost]
public ActionResult Something(IEnumerable<MyClass> items)
{ 
    //bla bla bla
}
Nestor
  • 8,194
  • 7
  • 77
  • 156
Garnyatar
  • 163
  • 1
  • 4
  • 10

2 Answers2

0

for my case I will do this way.

 foreach(var item in Model)
        {

               <input type="checkbox" name="removefromcart" value="@(item.Id)" />

                Html.DisplayFor(modelItem => item.Url);
            <br/>


        }

In my controller class

  public ActionResult UpdateWishlist(FormCollection form)
    {

        var allIdsToRemove = form["removefromcart"] != null 
            ? form["removefromcart"].Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(int.Parse)
            .ToList() 
            : new List<int>();
Anik Saha
  • 4,313
  • 2
  • 26
  • 41
0

You can try this.

  foreach(var item in Model)
  {
      <input type="checkbox" name="removefromcart" value="@item.Checked" />
      Html.DisplayFor(modelItem => item.Url);
      <br/>
  }

Then your controller can be modified to this.

[HttpPost]
public ActionResult Something(string[] removefromcart) //you will get all the values as string array.
{ 
    //bla bla bla
}

Here is a similar answer that might help you

Community
  • 1
  • 1
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59