我对函数进行了AJAX调用:
$('#DeviceType').change(function () {
// when the selection of the device type drop down changes
// get the new value
var devicetype = $(this).val();
$.ajax({
url: '@Url.Action("GetEquipmentCode")',
type: 'POST',
data: { deviceTypeID: devicetype },
success: function (result) {
// when the AJAX succeeds refresh the EquipmentCode text box
$('#EquipmentCode').val(result);
}
});
});
功能为
[HttpPost]
public string GetEquipmentCode(int deviceTypeID)
{
var deviceType = _db.DeviceTypes.Single(d => d.ID == deviceTypeID);
return (deviceType.EquipmentCode != null) ?
deviceType.EquipmentCode.Code :
String.Empty;
}
但是,如果函数返回String.Empty
,我在文本框中实际得到的字符串是“[object XMLDocument]
”。如何在文本框中获得空字符串的结果?
答案 0 :(得分:1)
尝试
....
data: { deviceTypeID: devicetype },
dataType : 'html',
...
默认情况下,jquery尝试猜测,有时可能不准确。
答案 1 :(得分:1)
JSON可能是最简单的。
尝试:
$('#DeviceType').change(function () {
// when the selection of the device type drop down changes
// get the new value
var devicetype = $(this).val();
$.ajax({
url: '@Url.Action("GetEquipmentCode")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: { deviceTypeID: devicetype },
success: function (result) {
// when the AJAX succeeds refresh the EquipmentCode text box
$('#EquipmentCode').val(result);
}
});
});
然后在你的ActionMethod
中[HttpPost]
public ActionResult GetEquipmentCode(int deviceTypeID)
{
var deviceType = _db.DeviceTypes.Single(d => d.ID == deviceTypeID);
return Json((deviceType.EquipmentCode != null) ?
deviceType.EquipmentCode.Code :
String.Empty);
}