Damkulul
Damkulul

Reputation: 1476

How to pass multiple parameters using web-api

I want to pass two params using json in web-api, but I get null each time I try, what am I missing ? is there a better way to pass more than one parameter?

//HTML

var uri = "api/Login";

//after I click a button this function fires

function checkUser() {
        var email = "[email protected]";   
       var password = "itsme";
          var details = "{ email:'"+ email+"', pass:'"+ password+"'}";           
        $.ajax({
            type: "Get",          
            data: JSON.stringify(details),
            url: uri,
            contentType: "application/json"
        });
    }

// LoginController

[HttpGet]
public HttpResponseMessage Get([FromBody]string  data)
{
     HttpResponseMessage msg = null;
     //the code run this function, but the 'data' is null
     string userinfo = data;                    
     return msg;
}

Upvotes: 0

Views: 1240

Answers (2)

Mike Brant
Mike Brant

Reputation: 71384

In addition to GET vs. POST issue noted by @su8898, you are already building a string in details and then trying to stringify it. You should define details as object literal like this:

var details = {
    'email': email,
    'pass': password
};

This would give you an actual object to stringify.

Upvotes: 1

su8898
su8898

Reputation: 1713

[FromBody] attribute won't work on GET requests because there is no body in a GET request.

You must either pass the values as parameters or change the method to [HttpPost]. I suggest you change the method to [HttpPost] and change your ajax request method to POST.

[HttpPost]
public HttpResponseMessage Get([FromBody]string  data)
{
    HttpResponseMessage msg = null;
    //the code run this function, but the 'data' is null
    string userinfo = data;                    
    return msg;
}

and in your ajax request

function checkUser() {
    var email = "[email protected]";   
    var password = "itsme";
      var details = "{ email:'"+ email+"', pass:'"+ password+"'}";           
    $.ajax({
        type: "POST",          
        data: JSON.stringify(details),
        url: uri,
        contentType: "application/json"
    });
}

Upvotes: 0

Related Questions