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

Retrieving ID of an item on CREATE

1 Answer 707 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Nse
Top achievements
Rank 1
Nse asked on 06 Jun 2016, 07:48 PM

I'm using the Kendo UI grid with ASP.NET Web API 2 to post some data to my server. There are 2 objects that are created by the server on CREATE; a work order and work order details. On CREATE the grid accesses the API and sends a work order of 0, telling my API that the work order is new. Once the work order is created, then the ID of the newly created work order is saved and the work order details are added to that work order as a child object. I want to return the ID of the newly created work order to the Grid so that the other rows following the first row use the new work order instead of creating a new work order for each row in the grid. As it is right now the grid sends a 0 to the API creating a new work order for each line item. Here is my code:

$("#grid").kendoGrid({
    dataSource: {
        batch: false,
        transport: {
            create: {
                // url: "http://localhost:53786/api/workorder/0/workorderdetails",
                url: function(workorder) {
                    var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
                    var WorkOrderDate = new Date($('#datepicker').val())
                    return 'http://localhost:53786/api/workorder/' + $('#ClientID').text() + '/' + $('#warehouse').val() + '/' + workorder.WorkOrderID + '/' + WorkOrderDate.getFullYear() + '/' + monthNames[WorkOrderDate.getMonth()] + '/' + WorkOrderDate.getDate() + '/1/workorderdetails';
                },
                contentType: "application/json",
                type: "POST"
            },
            read: {
                url: "http://localhost:53786/api/workorder/0/workorderdetails",
                dataType: "json"
            },
            update: {
                url: "http://localhost:53786/api/workorder/0/workorderdetails",
                dataType: "json",
                type: "PUT"
            },
            destroy: {
                url: function (workorderdetail) {
                    return "http://localhost:53786/api/workorder/1/workorderdetails" + workorderdetail.WorkOrderDetailID;
                },
                contentType: "application/json",
                type: "DELETE"
            },
            parameterMap: function (data, operation) {
                var output = null;
                switch (operation) {
                    case "create":
                        output = '{ ClientID: ' + $('#ClientID').text() + ', PriceCodeID: ' + data.ShortCode.PriceCodeID + ', Description: "' + data.ShortCode.Description + '", WorkOrderID: ' + data.WorkOrderID + ', Quantity: ' + data.Quantity + ', WorkOrderDate: "' + $('#datepicker').val() + ', WarehouseID: ' + $('#warehouse').val() + '" }';
                }
                // return JSON.stringify(data);
                return output;
            }
        },
        schema: {
            data: "Data",
            total: "Total",
            model: {
                id: "WorkOrderID",
                fields: {
                    WorkOrderID: { editable: "false", type: "number" },
                    ClientID: { type: "number" },
                    PriceCodeID: { type: "number" },
                    WorkOrderDetailID: { type: "number" },
                    ShortCode: { defaultValue: { PriceCodeID: 1436, ShortCode: "REF3" } },
                    Description: { type: "string" },
                    WorkOrderDate: { type: "string" },
                    Quantity: { type: "number" }
                }
            }
        }
    },
    pageable: true,
    allowCopy: true,
    height: 550,
    toolbar: ["create", "save", "cancel"],
    columns: [
        { field: "ShortCode", title: "Price Code", editor: shortcodeDropDownEditor, width: "150px", template: "#=ShortCode.ShortCode#" },
        { field: "Description", title: "Description", editable: "false" },
        { field: "Quantity", title: "Quantity", width: "100px" },
        { command: ["edit", "destroy"], width: "300px" }],
    editable: true,
    save: function(e) {
        if (e.values.hasOwnProperty('ShortCode')) {
            var test = e.model.set("Description", e.values.ShortCode.Description);
            var test = e.model.set("PriceCodeID", e.values.ShortCode.PriceCodeID);
        }                     
    },
    saveChanges: function (e) {
        if ($('#ClientID').text() === "") {
            e.preventDefault();
            alert("Please select a Client before saving the Work Order.");
        } else if ( Object.prototype.toString.call( $('#datepicker').val())) {
            e.preventDefault();
            alert("Please select a valid date before saving the Work Order.");
        }
        else {
            window.location.href = "http://localhost:53786/admin"
        }
    }
});

Here is the code for my API that gets called by the grid on CREATE:

<HttpPost, Route("api/workorder/{WorkOrderID:int}/workorderdetails")>
Public Function PostWorkOrderDetails(ByVal newWorkOrderDetail As WorkOrderDetail, WorkOrderID As Integer) As IHttpActionResult
 
    Dim newWorkOrder As New WorkOrder
 
    ' If a 0 is passed into the function then it's a new WorkOrder. We need to create it in this function
    If newWorkOrderDetail.WorkOrderID = 0 Then
 
        ' Fill in work order properties (omitted)
 
        _db.WorkOrders.Add(newWorkOrder)
        _db.SaveChanges()
 
    Else
        newWorkOrder = _db.WorkOrders.Find(WorkOrderID)
    End If
 
    ' Now that we have the new work order assign the work order detail to it.
    newWorkOrderDetail.WorkOrderID = newWorkOrder.WorkOrderID
 
    ' Add other properties to the object (omitted)
 
    _db.WorkOrderDetails.Add(newWorkOrderDetail)
    _db.SaveChanges()
 
    Dim response As HttpResponseMessage = Request.CreateResponse(HttpStatusCode.Created, newWorkOrderDetail)
    Return CreatedAtRoute("DefaultApi", New With {.WorkOrderID = newWorkOrderDetail.WorkOrderID}, newWorkOrderDetail)
 
End Function

 

 

 

1 Answer, 1 is accepted

Sort by
0
Boyan Dimitrov
Telerik team
answered on 08 Jun 2016, 11:22 AM

Hello Nse,

The Kendo UI DataSource differs newly created items and updating existing items  in the value of the WorkOrderID field. If the WorkOrderID value is  "0" the create method will be called, because it thinks it is a new item. 

The create api method should return the WorkOrderID value generated by the data base. I would suggest to take a look at the KendoGridWebApiCRUD project. 

Also there is a Use WebAPI with Server-Side Operations how-to article with Web API and Kendo UI Grid (not the MVC wrapper) that uses the type: "webapi" setting of the Kendo UI DataSource. 

Regards,
Boyan Dimitrov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Tags
Grid
Asked by
Nse
Top achievements
Rank 1
Answers by
Boyan Dimitrov
Telerik team
Share this question
or