2011-09-14 50 views
1

我有一个AJAX调用一个函数:返回一个空字符串到一个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]”。如何在我的文本框中获得空字符串的结果?

+1

是Ajax响应应该是XML或JSON?这是来自WCF还是MVC ActionMethod? – ericb

+0

MVC操作方法。而XML或JSON - 也许这是我应该返回而不是一个字符串? – link664

回答

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); 
} 
1

尝试

.... 
    data: { deviceTypeID: devicetype }, 
    dataType : 'html', 
    ... 

默认情况下,jQuery的试图猜测,有时可能不准确。

More info here

+0

只是将''text''改为''html'“ –

+0

看起来不起作用,仍然得到'[object XMLDocument]'。 – link664

相关问题