ajax - 将数据转换为 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);
}
}
解决方案
推荐阅读
- oracle - 矩阵报告总计随其行的每次增加或法令而变化
- marker - 在 Harp.gl 地图上放置一个标记
- sirishortcuts - Siri 快捷方式找不到子任务
- boost - 处理 INI 文件中重复的部分名称
- flutter - 跳转到颤振 sliverlist 中的特定 sliver
- git - 如何判断我的 Git LFS 迁移是否有效?
- python - 无法从 Google Drive 中的文本文件中获取内容
- c++ - 这个检查有效括号的函数的时间复杂度和空间复杂度是多少?
- javascript - How to trigger a javascript function when specific key is pressed on Keyboard?
- go - 我可以通过 golang 中的 http.FileServer 提供存储在 Google Cloud Storage 中的文件吗?