Josh
Josh

Reputation: 111

Passing multiple parameters in Ajax Call with Razor

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.

Upvotes: 1

Views: 2180

Answers (1)

Shyju
Shyju

Reputation: 218722

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.

Upvotes: 2

Related Questions