When enabling the row addition row in FlexGrid for ASP.NET MVC (AllowAddNew(true)), new rows initially render with empty or null cells. When adding new records, applications often require specific fields—such as IDs, dates, or default category labels—to pre-populate automatically rather than requiring manual user entry.
Solution
To initialize new rows with pre-populated values, use the NewItemCreator property within the grid's data binding setup, alongside the OnClientBeginningEdit event.
-
Define a JavaScript Creator Function: Create a client-side JavaScript function that returns a default data object containing your desired initial property values.
-
Assign
NewItemCreator: Pass the name of your creator function into.NewItemCreator("functionName")within theBind()configuration. -
Refresh the View on Edit: Handle the
OnClientBeginningEditclient-side event to calls.invalidate(), ensuring the grid view refreshes instantly to display the default values as soon as editing begins on the new row.
@* JavaScript Functions to Supply Default Values and Invalidate Layout *@
<script>
function newItemProvider(s, e) {
return {
h_idx: 5000,
h_name: "Default Category",
h_dept: "Sales"
};
}
function beginEdit(s, e) {
// Redraw grid on starting edit for row 0 (or new row location)
if (e.row == 0) {
s.invalidate();
}
}
</script>
@* FlexGrid Configuration in Razor Views *@
@(Html.C1().FlexGrid<Qbridge>()
.Id("PrintConFlexGrid1")
.AllowAddNew(true)
.NewRowAtTop(true)
.OnClientBeginningEdit("beginEdit")
.Bind(ib => ib
.Bind(Url.Action("DetailData"))
.DisableServerRead(true)
.NewItemCreator("newItemProvider")
)
.Columns(bl => {
bl.Add(cb => cb.Binding("h_idx").Header("idx").Width("50"));
bl.Add(cb => cb.Binding("h_name").Header("Name").Width("150"));
bl.Add(cb => cb.Binding("h_dept").Header("Department").Width("100"));
})
)