为了传递电子邮件地址,我使用的是带有POST类型的Ajax。
$.ajax({
url: "api/Search/UserByEmail",
type: "POST",
data: JSON.stringify({ emailAddress: userEmail }),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) { ... }
});
控制器:
[HttpPost]
public IEnumerable<Object> UserByEmail([FromBody] string emailAddress) { ... }
提琴手就是这样说的:
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]"}
为什么emailAddress参数始终为null?
最佳答案
// 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 });
}
使用formModel并将可序列化的属性放在类上,它将进行序列化
您的javascript自动转换为C#等效语言。而且您不需要使用Json-stringify。
请注意,删除了// contentType:“ application / json; charset = utf-8”,
ajax方法的声明。我实际上从未使用过它。
关于asp.net - Asp.net POST参数始终为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19132385/