1

So essentially, I'm building a web API, and I'm trying to use ajax to query a web service that accepts two arguments. I need to pass a List of Stings (SSNs) and I need to pass a single string to determine which environment it queries. ("a" for acceptance, and "i" for integration).

I'm using cshtml with razor. And so far this section is successfully giving me what I want from the divs.

var pInputSssns  = document.GetElementById(“SSNinput”).value;
var pTestRegion = document.GetElementById(“testRegion’).value;

However, just beneath it. I'm trying to insert both these params into an ajax call.

 $.ajax({
        type: 'GET',
        contentType: "application/json; charset=utf-8" 
        url: "myurl",
        data:"{}",
        success: function (data) {
            // populate a table
        }
    });

I've heard multiple opinions on how that can be done. Can I serialize them both as JSON, and then put two JSON objects in the data parameter? I've also heard that I can pass a c-sharp object, but if I try and do that I can't access the html variable while I'm inside the Razor code.

 @{ AjaxParam ap = new AjaxParam(); ap.pInputSsns = pInputSsns;}

Is there a good way to pass both of them in there? For reference, here's the Controller:

[ScriptMethod (ResponseFormat = Response Format.Json)] 
[System.Web.Http.HttpGet]
public JArray GetSSNAssociations([FromUri] List <string> pInputSsns, string pTestRegion)
{
\\ do something
}

Appreciate it everyone.

Josh
  • 115
  • 1
  • 15

1 Answers1

2

First, create a DTO class for the data you want to send.

public class SearchRequest
{
    public List<string> SsnList { set; get; }
    public string Environment { set; get; } 
}

Now in your WebApi controller's Post method will have this class as the parameter so that when the client sends a request, the default model binder will be able to map the request values to the properties of an object of this class.

public class ProductsController : ApiController
{
    public HttpResponseMessage Post([FromBody]SearchRequest req)
    {
       // I am simply returning the same object back. But you can do whatever you want
       // Check req.SsnList and req.Environment properties and do something useful.
        return Request.CreateResponse(HttpStatusCode.OK, req);
    }
}

Now from the client side code, You can build a javascript object which resemebles the structure of our DTO class and send it using jQuery ajax.

var model = { Environment: "I",  SssList: ["375329567", "3583345"] };
var url="../api/products";
$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: url,
    contentType: "application/json"
}).done(function (res) {
    console.log('res', res);
    // Do something with the result :)
});

Here is a post explaining the different options to send client side data to web api in detail.

I hardcoded the value of url variable. You should consider using the Html helper methods like Url.Action to generate the correct relative path to your app endpoint as explained in this post.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Ok, that seems reasonable thanks! I'll have to take a look at the links you provided, as well. My route is a 'GET' not a 'POST' but I don't think that should matter...? my only questions is, what's happening with "var model" in your third code block. I'm not hard coding those values. A little confused about what's happening there. – Josh May 06 '16 at 11:03
  • I just hard coded the values. You can read it from your Dom elements and build the same structure. Also, you should consider using post as get might not work for complex data. – Shyju May 06 '16 at 12:03
  • So I think that this has actually solved my problem. It's still not working because I'm having an issue with CORS, XMLHttpRequest cannot load http://localhost:64819/api/Participant/getssnassociations?{%22pInputSsns%22:[%xxxx-xx-xxxx--xxxx%22],%22pTestregion%22:%22a%22}. Response for preflight has invalid HTTP status code 405 So I'll have to work with that. But thanks! – Josh May 09 '16 at 15:10