I am coding a C# Web API 2
webservice where I am getting a simple object with some AJAX
code. The object is being returned correctly, however, if the exact same object has a [Serializable]
attribute, then the AJAX
code is not working correctly.
Here is the simple object:
public class Simple
{
public int number { get; set; }
public string data { get; set; }
}
Here is the AJAX
code:
function sendRequest() {
$.ajax({
type: 'GET',
url: serviceUrl2,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth(userName, password));
}
}).success(function (data) {
alert('Success');
alert('data:' + data.data);
}).error(function (jqXHR, textStatus, errorThrown) {
$('#value1').text(jqXHR.responseText || textStatus);
});
}
The above code works correctly, and an alert is shown with the data.
If the same object is coded as follows:
[Serializable]
public class Simple
{
public int number { get; set; }
public string data { get; set; }
}
The above code does not work correctly, and an alert is shown with "data:undefined"
Here is the Web API
function:
[System.Web.Http.HttpGet]
[Route("Getsimple")]
[ResponseType(typeof(Simple))]
public async Task<IHttpActionResult> GetSimple()
{
if (!User.Identity.IsAuthenticated)
{
}
var simple = new Simple();
simple.number = 1;
simple.data = "test data";
return Ok(simple);
}
Do I need to add a specific parameter to the AJAX
code or do I need to serialize the Simple
object before the object is returned? If not, how can I get the code working?