NSS
NSS

Reputation: 2022

Kendo UI Grid posting back already Inserted Rows again

I am running into problem, where when an Insert is completed successfully and if i continue to insert another row, in the next insert it is also sending the row that was inserted successfully earlier, so it goes like this. On the First insert that row is posted back to webAPI and inserted successfully. On Next Insert Two rows are sent one of them was from first step. On third Insert it send previous two rows as well as third row and so on.

What could be the cause of this ?

This is the Code in problem.

$(document).ready(function () {
try {

var degreeYearsArray = new Array();

function GetDegreeName(dgID, degreeName) {
    for (var i = 0; i < degreeYearsArray.length; i++) {
        if (degreeYearsArray[i].dgID_PK == dgID) {
            return degreeYearsArray[i].Name;
        }
    }
    return degreeName;
}

var degreeYearModel = {
    id: "DGYR_PK",
    fields: {
        DGID_FK: {
            type: "number",
            nullable: false,
            editable: false
        },
        Code: {
            type: "string",
            validation: {
                required: true,
                minlength: 2,
                maxlength: 160
            }
        },
        Year: {
            type: "number",
            validation: {
                required: true
            }
        },
        EffectiveDate: {
            type: "date",
            validation: true

        },
        TerminationDate: {
            type: "date",
            validation: true
        }
    }
}; 




var baseURL = "http://localhost:3103/api/Degree";
var degreeYearTransport = {
    create: {
        url: baseURL + "/PostDegreeYears", // "/PutOrgSchool",
        type: "POST",
        // contentType: "application/json"
        dataType: "json"
    },
    read: {
        url: function () {
            var newURL = "";
            if (window.SelectedDegree == null)
                newURL =   baseURL + "/GetDegreeYears"
            else
                newURL =  baseURL + "/GetDegreeYears?degreeID=" + window.SelectedDegree.DGID_PK;
            return newURL;
        },
       dataType: "json" // <-- The default was "jsonp"
    },
    update: {
        url: baseURL + "/PutDegreeYears", //"/PostOrgSchool",
        type: "PUT",
        // contentType: "application/json",
        dataType: "json"
    },
    destroy: {
        url: function (employee) {
            return baseURL + "/deleteOrg" + employee.Id
        },
        type: "DELETE",
        dataType: "json",
        contentType: "application/json"
    },
    parameterMap: function (options, operation) {
        try {


            if (operation != "read") {
                options.EffectiveDate = moment(options.EffectiveDate).format("MM-DD-YYYY");
                options.TerminationDate = moment(options.TerminationDate).format("MM-DD-YYYY")
            }
            var paramMap = kendo.data.transports.odata.parameterMap(options);

            delete paramMap.$format; // <-- remove format parameter.

            return paramMap;

        } catch (e) {
            console.error("Error occure in parameter Map or Degree.js" + e.message);
        }

    }
}; //transport




var dsDegreeYears = new kendo.data.DataSource({
    serverFiltering: true, // <-- Do filtering server-side
    serverPaging: true, // <-- Do paging server-side
    pageSize: 2,
    transport: degreeYearTransport,
    requestEnd: function (e) {
        try {
            if (e.type == "update"){
                $.pnotify({
                    title: 'Update Sucessful',
                    text: 'Record was Updated Successfully',
                    type: 'success'
                });
            }

            if (e.type == "create") {
                $.pnotify({
                    title: 'Insert Sucessful',
                    text: 'Record was Inserted Successfully',
                    type: 'success'
                });
            }
        } catch (e) {
            console.error("error occured in requestEnd of dsDegreeYears datasource in DegreeYears.js" + e.message);
        }

    },
    schema: {
        data: function (data) {
            return data.Items; // <-- The result is just the data, it doesn't need to be unpacked.
        },
        total: function (data) {
            return data.Count; // <-- The total items count is the data length, there is no .Count to unpack.
        },
        model: degreeYearModel
    }, //schema
    error: function (e) {
        var dialog = $('<div></div>').css({ height: "350px", overflow: "auto" }).html(e.xhr.responseText).kendoWindow({
            height: "300px",
            modal: true,
            title: "Error",
            visible: false,
            width: "600px"

        });

        dialog.data("kendoWindow").center().open();
    },

});


$("#" + gridName).kendoGrid({
    dataSource: dsDegreeYears,
    autoBind: false,
    groupable: true,
    sortable: true,
    selectable: true,
    filterable: true,
    reorderable: true,
    resizable: true,
    columnMenu: true,
    height: 430,
    editable: "inline",
    toolbar: ["create"],
    pageable: {
        refresh: true,
        pageSizes: true,
        buttonCount: 5
    },
    columns: [  {
                    field: "DGID_FK",
                    title: "Degree Name",
                    width: 140,
                    template: function (dataItem) {
                        if (window.SelectedDegree != null) {
                            dataItem.DGID_FK = window.SelectedDegree.DGID_PK;
                            return window.SelectedDegree.Name;
                        }
                        else
                            return "";
                    }
                },
                {
                    field: "Code",
                    title: "Code",
                    width: 140
                },
                 {
                     field: "Year",
                     title: "Year",
                     width: 140
                 },
               {
                   field: "Description",
                   width: 110
               },

            {
                field: "EffectiveDate",
                width: 110,
                format: "{0:MM/dd/yyyy}"
            },
            {
                field: "TerminationDate",
                width: 110,
                format: "{0:MM/dd/yyyy}"
            },

             {
                 command: ["edit"] , title: "&nbsp;", width: "172px"
             }
    ]
}); //grid

//Hide history pull-down menu in the top corner
$.pnotify.defaults.history = false;
$.pnotify.defaults.styling = "bootstrap";
// styling: 'bootstrap'
//styling: 'jqueryui'


} catch (e) {
    console.error("Error occured in DegreeYears" + e.message);
}

}); // document

This is the Response that is sent from WebAPI

 {"$id":"1","DGYR_PK":27,"DGID_FK":64,"Year":4,"Code":"4THYR","EffectiveDate":"2014-01-11T00:00:00","TerminationDate":"2014-01-11T00:00:00","CreatedByUserID_FK":1,"DateCreated":"0001-01-01T00:00:00","UpdatedByUserID_FK":1,"DateUpdated":"0001-01-01T00:00:00","RowStatusID_FK":1,"Degree":null,"DegreeYearExamSchedules":[],"User":null,"RowStatu":null,"User1":null,"DegreeYearSubjects":[]}

So i do see i am returning ID as suggested by the users in response to the question. still wondering

Upvotes: 2

Views: 2333

Answers (4)

Houdini Sutherland
Houdini Sutherland

Reputation: 1570

You can attached and respond to the requestEnd event on the DataSource.

requestEnd: function(e) {
        if (e.type === "create") {
            this.read();
        }
    }

What that is saying is: "After you created a record, reread the entries (including the newly created one) into the grid". Thereby giving you the newly created entry with key and all. Of course you see that the extra read may have some performance issue.

Upvotes: 2

Ross Bush
Ross Bush

Reputation: 15185

Your primary key cannot be 0 or null. If you are using auto-incrementing values then you should invoke the "re-read" of your dataSource after post. Check the values and make sure your data values are >0. Note: I have set the default value of the PK in the model to -1 in the column model to help with this.

Upvotes: 2

Atanas Korchev
Atanas Korchev

Reputation: 30671

This will happen if you don't return the "DGYR_PK" value of the newly inserted model. The data source needs a model instance to have its "id" field set in order not to consider it "new". When you return the "ID" as a response of the "create" operation the data source will work properly.

You can check this example for fully working Web API CRUD: https://github.com/telerik/kendo-examples-asp-net/tree/master/grid-webapi-crud

Here is the relevant code:

public HttpResponseMessage Post(Product product)
{
    if (ModelState.IsValid)
    {
        db.Products.AddObject(product);
        db.SaveChanges();

        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, product);
        response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = product.ProductID }));
        return response;
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

Upvotes: 4

chamara
chamara

Reputation: 12709

After you have inserted a record, you need to return the id of that row, otherwise grid consider the previous row as a new row too.

In your create function you call the web API

baseURL + "/PostDegreeYears", // "/PutOrgSchool",

In the server side consider the below code.

public void Create(ABSModel model)
        {
            try
            {
                using (context = new Pinc_DBEntities())
                {

                        tblAB tb = new tblAB();
                        tb.ABS = model.ABS;
                        tb.AreaFacility = model.AreaFacility;
                        context.tblABS.Add(tb);

                        Save();
                        model.ABSID = tb.ABSID;//this is the important line of code, you are returning the just inserted record's id (primary key) back to the kendo grid after successfully saving the record to the database.


                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

please adjust the above example according to your requirement.

Upvotes: 3

Related Questions