[RESOLVED]saving multiple checkbox selections into database records

I have a list of team with a checkbox each. the user should select several teams and when click save these selected items should be saved in the database.

table: teamTour: tourName,teamName

each checked box will be saved desperately in a record with a tour name.

Example: tourName   tourTeam

                USA               Brazil

               USA                 canada

                USA               bilgium

I can get the tourName , I just want the tourTeam selections.

this is my view for the tourTeams

<div class="form-group">
                <label class="col-md-2 control-label">
                    Select Participating Teams
                </label>
                <div class="col-md-10">
                    @foreach (var item in (SelectList)ViewBag.Teams)
                    {
                        <input type="checkbox" name="SelectedTeams" value="@item.Value" class="checkbox-inline" />
                        @Html.Label(item.Value, new { @class = "control-label" })
                    }
                </div>
            </div>

This is the controller where I am saving my tables

 public ActionResult create(Tournament tour,TourTeam teamtour)
        {
//the Tournament is a model for the tournament details such as name and schedule , and TourTeam is a model for tourName and selected teams
            if (ModelState.IsValid)
            {
                TourTeam newRecord = new TourTeam();
                newRecord.tourName = Request.Form["tourName"];
                newRecord.touTeam = //don't know what to write here
                db.Tournaments.Add(tour);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(tour);
        }

Hi lolo512,

Thanks for your post.

Try this:

newRecord.touTeam =teamtour.checkboxids.Select(x=> db.TourTeams.Find(x));

More information:

#ASP.NET MVC Binding a List of Values to a List of Checkboxes

http://www.andrewdenhertog.com/c/asp-net-mvc-binding-a-list-of-values-to-a-list-of-checkboxes/

#Checkbox in MVC

http://www.mindstick.com/Articles/2ee905ba-aea1-4d83-a49d-d8d8fb10c747/Checkbox%20control%20in%20MVC

Hope this can he helpful.

Best Regards,

Eileen

Eileen ni – MSFT

Try this:

newRecord.touTeam =teamtour.checkboxids.Select(x=> db.TourTeams.Find(x));

so I am supposed to have a checkboxids in my TourTeam model rather than the default id assigned in the database?

Hi,

lolo512

so I am supposed to have a checkboxids in my TourTeam model rather than the default id assigned in the database?

Yes.

Best Regards,

Eileen

Leave a Reply