首页 > 解决方案 > 将数据转换为 json.stringify 时,asp.net mvc 未从 ajax 获取值

问题描述

我正在使用一个事件处理程序来检查产品 ID 或名称是否已经存在。但我的问题是当我使用 JSON.stringify() 时,我的 C# 控制器没有从 ajax 调用接收数据。

 // check if Product name already exist
    $('#productName').bind('keyup blur', function () {
        // check if input is empty
        if ($(this).val().length > 0) {
            var data = JSON.stringify({
                value: $(this).val(),
                fieldName: 'productName'
            });
            $.ajax({
                type: "post",
                url: '/Product/ValidateProductDetailsExist',
                contenttype: "application/json; charset=utf-8",
                datatype: "json",
                data: data,
                context: this,
                success: function (result) {
                    if (result === true) {
                        // append error message
                        // check if error message already exist
                        if ($('#errorprodcutName').length === 0) {
                            var errormessage = '<div class="col-md-offset-2"><span id = "errorprodcutName" class="validation-error-message">Product name already exist</span></div >';
                            $('.form-group:nth-child(2)').append(errormessage);
                        }
                        $(this).focus();
                        //disables the save button
                        $('#btnSaveProduct').prop('disabled', true);
                    }
                    else {
                        // check if error message already exist
                        if ($('#errorprodcutName').length > 0) {
                            $('#errorprodcutName').remove();
                        }
                        //enables the save button
                        $('#btnSaveProduct').prop('disabled', false);
                    }
                },
                error: function () {
                    alert("unable to request from server");
                }
            });
        }
    });

当我使用调试器检查该值时,它为空。我也没有看到控制台中显示任何错误。谁能向我解释为什么它不起作用。

public JsonResult ValidateProductDetailsExist(string value, string fieldName)
    {
        using (POSEntities3 db = new POSEntities3())
        {
            bool isExist = false;

            switch (fieldName)
            {
                case "productId":
                    var dataItemProductId = db.Products.Where(product => product.product_id == value).SingleOrDefault();
                    isExist = (dataItemProductId != null);
                    break;
                case "productName":
                    var dataItemProductName = db.Products.Where(product => product.name == value).SingleOrDefault();
                    isExist = (dataItemProductName != null);
                    break;
            }

            return Json(isExist, JsonRequestBehavior.AllowGet);
        }
    }

标签: ajaxasp.net-mvcasp.net-ajax

解决方案


推荐阅读