I am struggling with ASP.NET MVC3 when trying to update data through the Entity Framework. The process is as follows:
I have this model:
public class Bet { public string BetID { get; set; } public int FixtureID { get; set; } public string Better { get; set; } public int GoalsHome { get; set; } public int GoalsGuest { get; set; } public virtual Fixture { get; set; } }
In the controller, I filter the table through the where clause to get only records matching the user:
[HttpGet] public ActionResult Index() { var user = User.Identity.Name; var model = _db.Bets.Where(t => t.Better == user); return View(model); }
The view consists of two parts that take care of the table headers, and the other - about all user bids:
<fieldset> <legend>Bets</legend> <table> <tr> <th> Kickoff </th> <th> Home Team </th> <th> Guest Team </th> <th> Group </th> <th> Bet </th> </tr> @Html.EditorFor(m => m)
The EditorTemplate:
@model Betting.Models.Bet <tr> <td> @Html.DisplayFor(modelItem => Model.Fixture.Kickoff) </td> <td> @Html.DisplayFor(modelItem => Model.Fixture.HomeTeam) </td> <td> @Html.DisplayFor(modelItem => Model.Fixture.GuestTeam) </td> <td> @Html.DisplayFor(modelItem => Model.Fixture.Group) </td> <td> @Html.TextBoxFor(modelItem => Model.GoalsHome, new { style = "width: 30px" }): @Html.TextBoxFor(modelItem => Model.GoalsGuest, new { style = "width: 30px" }) </td> @Html.HiddenFor(modelItem => Model.FixtureID) </tr>
Back to the controller I'm trying to update the model:
[HttpPost] public ActionResult Index(FormCollection collection) { var user = User.Identity.Name; var model = _db.Bets.Where(t => t.Better == user); TryUpdateModel(model); _db.SaveChanges(); return RedirectToAction("Index"); }
This is absolutely nothing. Entity Framework will not update the database at all. I even divided the table so that the received bid tags in the html file were distinguishable (note the [index] before the name value:
<input data-val="true" data-val-number="The field GoalsHome must be a number." data-val-required="The GoalsHome field is required." name="[1].GoalsHome" style="width: 30px" type="text" value="3" />: <input data-val="true" data-val-number="The field GoalsGuest must be a number." data-val-required="The GoalsGuest field is required." name="[1].GoalsGuest" style="width: 30px" type="text" value="0" />
Can someone tell me why the Entity Framework is not updating the database? Is there something wrong with displaying the object?