This is a migrated thread and some comments may be shown as answers.

Grid Create and Remove not refreshing

1 Answer 114 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Mike
Top achievements
Rank 1
Mike asked on 06 Nov 2013, 10:00 PM

I have a hierarchical grid where the child grid elements can be updated but the parent cannot but a calculated value needs to be updated via javascript from the refreshed child. When I edit the child grid elements all is well. If I create a new row the calculated value is updated correctly but the grid doesn't refresh and show the new row. Manually refreshing the grid makes the row appear.

Grid:

@(Html.Kendo().Grid<TimeAndAttendance.Models.DaysActivityViewModel>()
      .Name("grid_#=SelectedAssociateID#") // make sure the Name is unuque
      .Columns(columns =>
      {
          columns.Bound(ta => ta.BeginPeriod).Title("Alloc Period")
                                                .Format("{0:MM-dd-yyyy}");
          columns.Bound(ta => ta.OperatingUnit).Title("Operating Unit")
                                                .ClientTemplate("\\#: OperatingUnit.Description \\#")
                                                .EditorTemplateName("OperatingUnitEditor")
                                                .Visible(Model.TAColumns.OperatingUnitVisible);
          columns.Bound(ta => ta.Position).Title("Position")
                                                .ClientTemplate("\\#: Position.Description \\#")
                                                .EditorTemplateName("PositionEditor")
                                                .Visible(Model.TAColumns.PositionVisible);
          columns.Bound(ta => ta.Department).Title("Department")
                                                .ClientTemplate("\\#: Department.Description \\#")
                                                .EditorTemplateName("DepartmentEditor")
                                                .Visible(Model.TAColumns.DepartmentVisible);
          columns.Bound(ta => ta.Shift).Title("Shift")
                                                .ClientTemplate("\\#: Shift.Description \\#")
                                                .EditorTemplateName("ShiftEditor")
                                                .Visible(Model.TAColumns.ShiftVisible);
          columns.Bound(ta => ta.Paycode).Title("Paycode")
                                                .ClientTemplate("\\#: Paycode.Description \\#")
                                                .EditorTemplateName("PaycodeEditor")
                                                .Visible(Model.TAColumns.PaycodeVisible);
          columns.Bound(ta => ta.Tier).Title("Tier")
                                                .ClientTemplate("\\#: Tier.Description \\#")
                                                .EditorTemplateName("TierEditor")
                                                .Visible(Model.TAColumns.TierVisible);
          columns.Bound(ta => ta.Level).Title("Level")
                                                .ClientTemplate("\\#: Level.Description \\#")
                                                .EditorTemplateName("LevelEditor")
                                                .Visible(Model.TAColumns.LevelVisible);
          columns.Bound(ta => ta.Wage).Title("Wage")
                                                .ClientTemplate("\\#: Wage.Description \\# <input type='button' style='float:right;color:Red' onclick='override(this, \\#:ID\\#);' value='Override'/>")
                                                .Visible(Model.TAColumns.WageVisible);
          columns.Bound(ta => ta.Hours).Format("{0:n2}").EditorTemplateName("Number");
          columns.Bound(ta => ta.Notes);
          columns.Bound(ta => ta.Status).ClientTemplate("\\#: Status.Description \\#");
          columns.Command(command => { command.Edit().Text(""); command.Destroy().Text(""); }).Visible(Model.TAColumns.ShowEditDelete);
          columns.Command(command =>
          {
              command.Custom("reject").Text("Reject").Click("rejectPrompt");
              command.Edit().Text("");
          })
                .Visible(Model.TAColumns.ShowWageReject);
      })
      .DataSource(dataSource =>
          dataSource.Ajax()
          .Read(read => read.Action("TimeAllocations", "TeamTimeEntry", new { assocID = "#=SelectedAssociateID#" }).Data("getReadParameters"))
          .Update(update => update.Action("Edit", "TeamTimeEntry", new { assocID = "#=SelectedAssociateID#" }))
          .Destroy(destroy => destroy.Action("Delete", "TeamTimeEntry", new { assocID = "#=SelectedAssociateID#" }))
          .Create(create => create.Action("Create", "TeamTimeEntry", new { assocID = "#=SelectedAssociateID#" }).Data("getReadParameters"))
          .Model(model =>
          {
              model.Id(ia => ia.ID);
              model.Field(field => field.BeginPeriod).Editable(false);
              model.Field(field => field.Status).DefaultValue(Model.Statuses.FirstOrDefault()).Editable(false);
              model.Field(field => field.OperatingUnit).DefaultValue(Model.OperatingUnits.FirstOrDefault()).Editable(Model.TAColumns.OperatingUnitVisible);
              model.Field(field => field.Shift).DefaultValue(Model.Shifts.FirstOrDefault()).Editable(Model.TAColumns.ShiftVisible);
              model.Field(field => field.Department).DefaultValue(Model.Departments.FirstOrDefault()).Editable(Model.TAColumns.DepartmentVisible);
              model.Field(field => field.Paycode).DefaultValue(Model.Paycodes.FirstOrDefault()).Editable(Model.TAColumns.PaycodeVisible);
              model.Field(field => field.Position).DefaultValue(Model.Positions.FirstOrDefault()).Editable(Model.TAColumns.PositionVisible);
              model.Field(field => field.Tier).DefaultValue(Model.Tiers.FirstOrDefault()).Editable(Model.TAColumns.TierVisible);
              model.Field(field => field.Level).DefaultValue(Model.Levels.FirstOrDefault()).Editable(Model.TAColumns.LevelVisible);
              model.Field(field => field.Wage).DefaultValue(Model.Wages.FirstOrDefault()).Editable(false);
          })
      )
      .ToolBar(toolbar =>
                toolbar.Create().Text("New Time Allocation")
                )
      .Events(events =>
                events.Save("save")
                    .Remove("remove")
                    .DataBound("childDataBound"))
      .ToClientTemplate())

JavaScript:

function updateVarianceDisplay(e) {
    var grid = $('#TimeAllocations').data('kendoGrid');
    var row = $(e.sender.element[0]).parent().parent().parent().parent().prev();
    var dataItem = grid.dataItem(row);
    if (dataItem != null) {
        var childGrid = $('#grid_' + dataItem.SelectedAssociateID).data('kendoGrid');
        var totalHoursAssigned = 0;
        var variance = 0;
        $(childGrid._data).each(function (index, value) {
            totalHoursAssigned += value.Hours;
        });
        dataItem.set("TotalHoursAssigned", totalHoursAssigned);
        variance = dataItem.PeriodHoursWorked - totalHoursAssigned;
 
        var varianceMessageHTML = printVariance(variance);
        var varianceHTML = colorCodeUnassigned(variance);
 
        $('[id^="fntUnassigned:' + dataItem.SelectedAssociateID + '"]').html(varianceHTML);
        $('[id^="fntVariance:' + dataItem.SelectedAssociateID + '"]').html(varianceMessageHTML);
 
        dataItem.set("UnassignedHours", variance);
    }
}
 
function save(e) {
    updateVarianceDisplay(e);
}
 
function remove(e) {
    updateVarianceDisplay(e);
}

Controller:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Create([DataSourceRequest]DataSourceRequest request, int assocID, DaysActivityViewModel viewModel, string SelectedFacilityID, string begingPeriod)
{
    TimeAllocation ta = new TimeAllocation()
    {
        ModifiedBy = HttpContext.User.Identity.Name,
        AssociateID = assocID,
        Created = DateTime.Now,
        DepartmentID = (short?)viewModel.Department.ID,
        FacilityAccountID = (short?)viewModel.OperatingUnit.ID,
        ShiftID = viewModel.Shift.ID,
        PositionID = (short)viewModel.Position.ID,
        Hours = (decimal)viewModel.Hours,
        PayCodeID = (short)viewModel.Paycode.ID,
        Period = viewModel.BeginPeriod, //RGM 09-05-13 Does the TimeAllocation
        StatusID = 1
    };
    db.TimeAllocations.AddObject(ta);
    db.SaveChanges();
 
    viewModel.FacilityAccount = db.FacilityAccounts.Where(f => f.ID == ta.FacilityAccountID).FirstOrDefault().OperatingUnit;
 
    if (!string.IsNullOrEmpty(viewModel.Notes))
    {
        Note n = new Note() { Note1 = viewModel.Notes, CreatedBy = User.Identity.Name, Created = DateTime.Now };
        db.Notes.AddObject(n);
        db.SaveChanges();
 
        TimeAllocationNote tan = new TimeAllocationNote()
        {
            NoteID = n.ID,
            //NoteTypeID = db.NoteTypes.Where(nt => nt.Description == "Time Allocation Note").Single().ID,
            TimeAllocationID = ta.ID
        };
        db.TimeAllocationNotes.AddObject(tan);
        db.SaveChanges();
    }
    viewModel.ID = ta.ID;
    return this.Json(new[] { viewModel }.ToDataSourceResult(request));
}

Also, the remove function does the opposite. The row is removed but the data in the JavaScript still contains the old row so the calculation is off. The grid and JavaScript for this are above, the controlled code is below.

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Delete([DataSourceRequest]DataSourceRequest request, int assocID, DaysActivityViewModel viewModel)
{
    if (db.TimeAllocations.Where(ta => ta.ID == viewModel.ID).FirstOrDefault().TimeAllocationNotes.FirstOrDefault() != null)
    {
        long noteID = db.TimeAllocations.Where(ta => ta.ID == viewModel.ID).FirstOrDefault().TimeAllocationNotes.FirstOrDefault().NoteID;
        long tanID = db.TimeAllocations.Where(ta => ta.ID == viewModel.ID).FirstOrDefault().TimeAllocationNotes.FirstOrDefault().ID;
        db.Notes.DeleteObject(db.Notes.Where(n => n.ID == noteID).FirstOrDefault());
        db.TimeAllocationNotes.DeleteObject(db.TimeAllocationNotes.Where(tan => tan.ID == tanID).FirstOrDefault());
    }
    db.TimeAllocations.DeleteObject(db.TimeAllocations.FirstOrDefault(t => t.ID == viewModel.ID));
    db.SaveChanges();
 
    viewModel = new DaysActivityViewModel();
 
    return Json(new[] { viewModel }.ToDataSourceResult(request, ModelState));
}

Thanks for any pointers as to what I am doing wrong.

1 Answer, 1 is accepted

Sort by
0
Mike
Top achievements
Rank 1
answered on 07 Nov 2013, 08:33 PM
I found the problem myself by creative debugging. In the OP's JavaScript there are 2 calls to dataItem.set. Those update calculated values in the parent row of the hierarchical grid. That apparently is a bad idea. They were in some manner breaking the child grids ability to refresh itself after update. Maybe someone from Telerik can explain why. Regardless, I chose to update just the HTML for now and everything works fine. Not the best solution but workable.
Tags
Grid
Asked by
Mike
Top achievements
Rank 1
Answers by
Mike
Top achievements
Rank 1
Share this question
or