I have a model with two field (Code and Item). The Code is set to auto increment and the Item is a required field. When I clicked the Add New Record button, the Code column was set to 0 in the Popup. After I add a new record, the Code field in the grid was set to 0 even I return the model with the new record.
Model:
public partial class HousenMokutekiD
{
public int Code { get; set; }
[Required]
[StringLength(20, MinimumLength = 3)]
public string Item { get; set; }
}
Controller:
public ActionResult Create([DataSourceRequest]DataSourceRequest request, HousenMokutekiD model)
{
if (string.IsNullOrWhiteSpace(model.Item))
{
ModelState.AddModelError("", "Item is required.");
}
if (model != null && ModelState.IsValid)
{
var entity = new HousenMokutekiD();
if (model.Item != null)
{
entity.Item = model.Item;
}
_context.HousenMokutekiD.Add(entity);
_context.SaveChanges();
model.Code = entity.Code;
model.Item = entity.Item;
}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
Razor:
@model IEnumerable<Sms.Office.Data.PmsDd.Models.HousenMokutekiD>
@(Html.Kendo().Grid(Model)
.Name("grid")
.Columns(columns =>
{
columns.Command(command =>
{
command.Edit().UpdateText("Save Changes");
command.Destroy();
}).Width(162);
columns.Bound(p => p.Code);
columns.Bound(p => p.Item);
})
.ToolBar(add =>
{
add.Create();
})
.Editable(editable =>
{
editable.Mode(GridEditMode.PopUp);
editable.Window(w => w.Title(""));
})
.Events(e =>
{
e.Edit("onEdit");
})
.Navigatable()
.Pageable()
.Sortable()
.Selectable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.PageSize(7)
.Events(events =>
{
events.Error("error_handler");
events.RequestEnd("request_end");
})
.Model(model =>
{
model.Id(p => p.Code);
})
.Read(read => read.Action("Read", "Purpose"))
.Create(create => create.Action("Create", "Purpose").Type(HttpVerbs.Post))
.Update(update => update.Action("Update", "Purpose").Type(HttpVerbs.Put))
.Destroy(destroy => destroy.Action("Destroy", "Purpose").Type(HttpVerbs.Delete))
)
)
Please help me. Sorry I am a newbee in MVC