简体   繁体   English

Kendo UI Grid添加新记录而不将数据发布到服务器端

[英]Kendo UI Grid adding new record not posting data to server side

I am working on Kendo UI jQuery grid CRUD. 我正在研究Kendo UI jQuery网格CRUD。 I can get data display in the grid, but not adding new records. 我可以在网格中显示数据,但不能添加新记录。

When I click the update button to add a record after filling up columns in the pop-up window, nothing is posted to the server side as every property has a null value. 当我在弹出窗口中填满列后单击更新按钮以添加记录时,没有任何内容发布到服务器端,因为每个属性都有一个空值。 The picture shows what I got when the button is pressed. 图片显示了按下按钮后得到的内容。

在此处输入图片说明

Controller: 控制器:

[HttpPost]
public JsonResult AddLostProperty(LostPropertyViewModel lostProperty)
{
    try
    {
        using (var dbContext = new DBEntities())
        {
            if (lostProperty != null)
            {
                var newLostProperty = new sz_LostProperty()
                {
                    Name = lostProperty.PropertyName,
                    CategoryId = dbContext.sz_PropertyCategory.Where(x => x.Name == lostProperty.CategoryName).Select(c => c.Id).FirstOrDefault(),
                    Description = lostProperty.PropertyDescription,
                    FoundDate = lostProperty.FoundDate,
                    FoundLocation = lostProperty.FoundLocation,
                    CratedDate = DateTime.UtcNow.Date,
                    CratedBy = ""
                };

                dbContext.sz_LostProperty.Add(newLostProperty);
                dbContext.SaveChanges();

                return Json(new { Success = true, Message = "The Property has been added." });
            }
            else
            {
                return Json(new { Success = false, Message = "No lost property added." });
            }
        }
    }            
    catch (Exception e)
    {
        return Json(new { Success = false, Message = "Error: " + e });
    }
}

JavaScript: JavaScript:

<script>
    $(document).ready(function () {
        var serviceBaseUrl = "@Request.Url.ToString()",
            lostPropertyDataSource = new kendo.data.DataSource({
                transport: {
                    create: {
                        url: serviceBaseUrl + "/AddLostProperty",
                        type: "POST",
                        dataType: "json",
                        complete: function (e) {
                            $('#manageLostPropertiesGrid').data('kendoGrid').dataSource.read();
                        }
                    },
                    read: {
                        url: serviceBaseUrl + "/GetLostProperties",
                        type: "GET",
                        dataType: "json"
                    },
                    update: {
                        url: serviceBaseUrl + "/UpdateLostProperty",
                        type: "PUT",
                        dataType: "json"
                    },
                    destroy: {
                        url: serviceBaseUrl + "/DeleteLostProperty",
                        type: "DELETE",
                        dataType: "json"
                    },
                    parameterMap: function (options, operation) {
                        if (operation !== "read" && options.models) {
                            return { models: kendo.stringify(options.models) };
                        }
                    }
                },
                batch: true,
                pageSize: 20,
                schema: {
                    model: {
                        id: "PropertyId",
                        fields: {
                            PropertyId: { editable: false, nullable: true, type: "number" },
                            PropertyName: { type: "string", editable: true, validation: { required: true } },
                            CategoryId: { type: "number", editable: true, validation: { required: true } },
                            PropertyDescription: { validation: { required: false } },
                            Image: { validation: { required: false } },
                            FoundDate: { type: "Date" },
                            FoundLocation: { editable: true, validation: { required: false } }
                        }
                    }
                }
            });

        $("#manageLostPropertiesGrid").kendoGrid({
            dataSource: lostPropertyDataSource,
            pageable: true,
            height: 550,
            toolbar: ["create"],
            columns: [
                { field: "PropertyName", title: "Property Name", width: "150px" },
                { field: "CategoryName", title: "Category", editor: propertyCategoryList,/* template: "#=CategoryName#", */width: "150px"},
                { field: "PropertyDescription", title: "Description", width: "200px" },
                { field: "FoundDate", title: "Found Date", template: "#= kendo.toString(kendo.parseDate(FoundDate, 'dd-MM-yyyy'), 'dd-MM-yyyy') #",  width: "130px" },
                { field: "FoundLocation", title: "Found Location", width: "120px" },
                { command: ["edit", "destroy"], title: "&nbsp;", width: "250px" }],
            editable: "popup"
        }).data("kendoGrid");
});

From the browser, I can see the object sent to the server below: 从浏览器中,我可以在下面看到发送到服务器的对象:

在此处输入图片说明

What am I doing wrong? 我究竟做错了什么?

I believe that in this case is problem in your parameter type at server side. 我认为在这种情况下,服务器端的参数类型存在问题。

You have enabled batch: true editing which is useful if you want make many changes in your grid but send only one request with changed models in the end. 您已启用批处理:真正的编辑,如果您想在网格中进行许多更改,但最后只发送一个更改了模型的请求,这将很有用。 It is very useful for example in case of inCell edit mode, when you would see many many requests and so decrease them is something you want, but in case of popup edit, I personally do not see any reason to use batch editing, but yes, I know Telerik has this in their demo. 例如,在inCell编辑模式下,这非常有用,当您看到许多请求并希望减少它们时就可以了,但是在弹出编辑的情况下,我个人看不到使用批处理编辑的任何理由,但是可以,我知道Telerik在他们的演示中有此内容。

So, because batch editing is enabled, there is called parameterMap before request is executed. 因此,由于启用了批量编辑,因此在执行请求之前调用了parameterMap (note: parameterMap is called only if you have batch edit enabled, otherwise it's ignored). (注意:仅当您启用了批量编辑时,才会调用parameterMap,否则它将被忽略)。 That parameterMap wraps all your models into json string array and send that array with request to the server. 该parameterMap将所有模型包装到json字符串数组中,并将带有请求的数组发送到服务器。 In your case, there is always one record edited, but it doesn't matter - it will be sent as an array (in json string format). 在您的情况下,总会编辑一条记录,但这没关系-它会以数组形式(以json字符串格式)发送。

Because it is sent as serialized string, you can 因为它是作为序列化字符串发送的,所以您可以

1) Change parameter of your AddLostProperty method to string models and then deserialize into array which allows you to work with it as you are used to 1)将您的AddLostProperty方法的参数更改为字符串模型 ,然后反序列化为数组,这使您可以像以前那样使用它

public ActionResult AddLostProperty(string models)
{
    ...
    var data = JsonConvert.DeserializeObject<IEnumerable<LostPropertyViewModel>>(models);
    ...
}

2) If we will follow Telerik demo, you can use such implementation 2)如果我们将遵循Telerik演示,则可以使用此类实现

public ActionResult AddLostProperty()
{
    var products = this.DeserializeObject<IEnumerable<LostPropertyViewModel>>("models");
    if (products != null)
    {
        //logic
    }
    return this.Jsonp(products);
}

3) And this is solution I would prefer 3)这是我更喜欢的解决方案

Just remove batch: true and parameterMap (since without batch it's useless) - and it should start send single object to your server method. 只需删除批处理:trueparameterMap (因为没有批处理就没有用了)-它应该开始将单个对象发送到您的服务器方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM