简体   繁体   中英

How to update a record in Entity Framework using checkbox

I am trying to update a record using EF. In my view I have used checkboxes to update multiple records. I have 2 problems 1)How to pass the edited textbox vales from view to controller and update those vales? 2)Every time when I edit something and update it is adding old data instead of updating the existing one.

View :

 @if (Model.Count > 0) { <div> @foreach (var books in Model) { <div class="col-md-2"> @Html.EditorFor(model => books.caption) @Html.ValidationMessageFor(model => books.caption) </div> <div class="col-md-2"> @Html.EditorFor(model => books.copies) @Html.ValidationMessageFor(model => photos.copies) </div> <div class="col-md-1"> <input type="checkbox" class="checkboxes" value="@books.id" name="id" /> </div> } </div> } <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" name="submitButton" value="UPDATE" /> <input type="submit" name="submitButton" value="ADD"/> <input type="submit" name="submitButton" value="DELETE" /> </div> </div> 

Controller :

public ActionResult EditBooks(int id, IEnumerable<int> id, string submitButton, [Bind(Include = "id,caption,copies")] Books books)
{
        if (ModelState.IsValid)
        {
            try
            {
                foreach (var item in id)
                {
                    var update = _db.Books.FirstOrDefault(s => s.id == item);

                    if (update != null)
                    {
                        _db.MyTable.Add(update);
                        _db.SaveChanges();
                    }

                    return RedirectToAction("Edit", new {id});
                }
            }
        }
}

According your logic you will add new record instead of updated. You can just analyze this bit of code:

_db.MyTable.Add(update);

According to entity framework logic you will put update item into EF action collection. EF操作”集合中。 So to fix it you need modify that bit of code to:

_db.MyTable.Update(update);

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