我很難找出為什么通過 AJAX 請求發送的字串為空。Console.WriteLine(data) 顯示為空。狀態為 200 OK。如果我添加一些代碼來決議收到的字串,我會收到一條錯誤訊息,指出 JObject.Parse 不能為空。我不知道我錯過了什么。javascript代碼沒問題。動作方法似乎還可以,但是我對 Asp.Net Core 和 MVC 的了解非常少,所以我不確定。有人可以指出我錯過了什么嗎?
javascript代碼:
let obj = {email: email_address.value};
let objStringified = JSON.stringify(obj);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=UTF-8',
data: objStringified,
url: '@Url.Action("ReturnCheckAccountDuplication")',
dataType: 'text',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
C#代碼:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] string data)
{
Console.WriteLine(data);
JObject jObject = JObject.Parse(data);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}
uj5u.com熱心網友回復:
最簡單的解決方案是創建一個模型來表示控制器將接收的 JSON 資料。例如,像這樣創建一個類:
public class AccountCheckModel
{
public string email { get; set }
}
然后,將其用作控制器方法的引數:
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
這是訪問請求正文的首選方式。要將請求正文作為字串獲取,您必須跳過一些嚴重的問題。
uj5u.com熱心網友回復:
將資料發送AJAX到您的另一種方法Controller:
var json = {
email: email_address.value
};
$.ajax({
type: 'POST',
data: {'json': JSON.stringify(json)},
url: '@Url.Action("ReturnCheckAccountDuplication")',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
你的Controller:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication(string json)
{
Console.WriteLine(json);
JObject jObject = JObject.Parse(json);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/419452.html
標籤:
