Reputation: 710
I'm using a MVC project with Visual Studio 2012 and Kendo UI 2014.
I can update a row from the grid and it changes, but when I reload the page, the row appears with the original info. I would like to update it in the database too.
This is my code:
.cshtml (View):
<div class="grid">
@(Html.Kendo().Grid<UsersModel>()
.Name("grid")
.Editable(editable => editable.Mode(GridEditMode.InCell))
.DataSource(dataSource => dataSource
.Ajax()
.Model(r => r.Id(p => p.Id))
.Read(r => r.Action("GetAccounts", "ManagerAccounts", new { area = "Admin" }))
.Destroy("Delete", "ManagerAccounts")
.Update("Update", "ManagerAccounts")
.Create("Create", "ManagerAccounts")
)
.Columns(columns =>
{
columns.Bound(c => c.Id);
columns.Bound(c => c.UserName);
columns.Bound(c => c.Email);
columns.Command(command => command.Destroy()).Width(120);
})
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5)
)
.Sortable()
.Navigatable()
.ToolBar(toolbar => {
toolbar.Create();
toolbar.Save();
})
)
</div>
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Update([DataSourceRequest] DataSourceRequest request, IEnumerable<UsersModel> users)
{
if (users != null && ModelState.IsValid)
{
foreach (var user in users)
{
AccountRepository.UpdateUsuarios(user);
}
}
return Json(ModelState.ToDataSourceResult());
}
Repository (AccountRepository):
public void UpdateUsuarios(UsersModel user)
{
var usuario = this.Context.Users.Where(l => l.Id == user.Id).FirstOrDefault();
if (usuario != null)
{
usuario.Id = user.Id;
usuario.UserName = user.UserName;
usuario.Email = user.Email;
this.Context.SaveChanges();
}
}
I tried with this.Context.SaveChanges();
but it doesn't work.
Upvotes: 1
Views: 2370
Reputation: 277
Could you please try this code:
if (usuario != null)
{
usuario.Id = user.Id;
usuario.UserName = user.UserName;
usuario.Email = user.Email;
this.Context.Entry(usuario).State = System.Data.Entity.EntityState.Modified;
this.Context.SaveChanges(); // Or you may try await this.Context.SaveChangesAsync();
}
Upvotes: 1