Reputation: 1095
For passing an email address I'm using ajax with POST as type.
$.ajax({
url: "api/Search/UserByEmail",
type: "POST",
data: JSON.stringify({ emailAddress: userEmail }),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) { ... }
});
Controller:
[HttpPost]
public IEnumerable<Object> UserByEmail([FromBody] string emailAddress) { ... }
That's what Fiddler says:
POST http://localhost:52498/api/Search/UserByEmail HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json;charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:52498/#
Accept-Language: de-DE
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Host: localhost:52498
Content-Length: 35
DNT: 1
Connection: Keep-Alive
Pragma: no-cache
{"emailAddress":"[email protected]"}
Why is the emailAddress parameter always null?
Upvotes: 3
Views: 3719
Reputation: 5219
Modify the data property in the original ajax call to
data: '"' + userEmail + '"',
Getting some of these Web API calls to work can sometimes be a little tricky
Upvotes: 0
Reputation: 10992
// JS - jQuery
$.ajax({
url: "/Home/UserByEmail",
type: "POST",
data: { emailAddress: "[email protected]" },
dataType: "json",
success: function (data) { if(data != null) { alert(data.toString()); } }
});
[Serializable]
public class EmailFormModel {
public string emailAddress { get; set; }
}
[HttpPost]
public JsonResult UserByEmail(EmailFormModel emailFormModel)
{
bool ok = emailFormModel.emailAddress != null;
return Json(new { ok });
}
Use a formModel and put a serializable attribute on the class and it will serialize your javascript automatically to a C# equivalent. And you don't need to use Json-stringify.
Note a removed the // contentType: "application/json;charset=utf-8", declaration from the ajax-method. I've actually never used it.
Upvotes: 1
Reputation: 56429
I think the JSON.stringify
could be your problem. MVC will handle the serialization/deserialization of parameters for you, change it to:
data: { emailAddress: userEmail }
Upvotes: 0