I am relatively new to working with Javascript, jQuery, and Ajax, so I have a few inquiries.
What I am hoping to achieve is as follows: I would like to make an Ajax request in my javascript code, where the controller will accept an OBJECT as a parameter. Upon receiving the backend response as a stream, the Controller should then return the result in JSON format (upon successful execution in the javascript). However, I am a little uncertain about whether to return JObject or raw JSON string (possibly using JsonConvert)?
In my WebApiConfig.cs file:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
The object type within the Controllers parameter list:
public class Credentials
{
public string Email { get; set; }
public int CustomerID { get; set; }
public string Reference { get; set; }
}
Controller method that needs to be invoked:
public HttpResponseMessage GetOrderInfo(Credentials credentials)
{
// Create URL with appended Credential properties
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
var response = (HttpWebResponse)httpWebRequest.GetResponse();
var responseStream = response.GetResponseStream();
var rawJson = new StreamReader(responseStream).ReadToEnd();
// var json = JObject.Parse(rawJson);
return Request.CreateResponse(HttpStatusCode.OK, rawJson);
}
Javascript snippet:
function get_order_info(email, customerId, reference) {
/* This is where I want to send an Ajax call to the designated controller, passing an object as a parameter */
}
Now, onto my questions:
How should the $Ajax call be structured if I want a specific Controller method that accepts a Credential object as a parameter?
Am I following the correct approach for returning data in JSON format from the Controller method GetOrderInfo?
Lastly, how can I access the returned JSON format in the success function of the response:
success: function (response) {
/* response.responseText ?? */
}
Thank you and best regards.