1

I am trying to implement a checkboxlist in my MVC application. here I need to get the selected checkboxlist values pass it to @html.ActionLink().
I have searched many sites including Stackoverflow but there is no model binding of database values and getting the selected checkbox values and passing to an action.
Eg :https://stackoverflow.com/questions/4872192/checkboxlist-in-mvc3-0

and I tried from this link. CheckBoxList multiple selections: how to model bind back and get all selections?

How to get the selected productid from the checkbox list. Any examples.. ??

Community
  • 1
  • 1
kk1076
  • 1,740
  • 13
  • 45
  • 76

1 Answers1

3

view:

@foreach (var item in Model.Tags)
{ <label>
      <input type="checkbox" name="tag" value="@item.TagID" @if (item.Selected) { <text>checked="checked"</text> } />@item.Name
  </label>
}

controller:

    [HttpPost]
    public RedirectToRouteResult Edit(IEnumerable<Guid> tag)
    {
        using (var dc = new MyDataContext())
        {
            var existing = dc.Tag
                .Select(i => i.TagID)
                .ToList();

            // remove old
            foreach (var id in existing.Except(tags.EmptyIfNull()))
                dc.Tag.DeleteOnSubmit(dc.Tag.Single(k => k.TagID == id);

            // add new
            foreach (var id in tags.EmptyIfNull().Except(existing))
                dc.Tag.InsertOnSubmit(new Tag() { TagID = id, });

            dc.SubmitChanges();
        }

        return RedirectToAction("List");
    }
andleer
  • 22,388
  • 8
  • 62
  • 82