I am struggling with ASP.NET MVC3 when trying to update data via Entity Framework. The process is as followed:
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 via a where statement to get only the entrys that match 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 is two parts, one that takes care of the table headers, and the other that lists all bets of the user:
<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) //this is resolved in an self made EditorTemplate
</table>
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 in the controller I try 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 does absolutely nothing. The Entity Framework won't update the database at all. I even separated the table so that the resulting bet tags in the html file will be 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 somebody tell me why the Entity Framework isn't updating the database? Is there something wrong with the object mapping?
TryUpdateModel? Or examinedModelStatefor any errors?