[英]Javascript, Ajax : Bad Request 400
I'm working on ASP Net Core Project and I'm trying to send to my controller with JQuery Ajax function from a partial view modal, parameters.
恢復的 URL 是正確的例如: http://localhost:44321/Validations/ValidationRefuse?ficheId=24&commentaire=Commentaire%20de%20test
但它總是:加載資源失敗:服務器響應狀態為 400(錯誤請求)
我的 Javascript:
$("#buttonRefusFiche").click(function (e) {
ficheId = $("#ficheId").val();
commentaire = $("#inputCommentaire").val();
$.ajax({
url: "/Validations/ValidationRefuse?ficheId=" + ficheId + "&commentaire" + commentaire,
type: 'POST',
contentType: 'application/html',
cache: true,
success: function () {
alert("Validation refusée.");
},
error: function () {
}
})
});
我的 C# 方法:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ValidationRefuse(int ficheId, string commentaire)
{ ... }
我的部分觀點:
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Validez-vous cette fiche ?</h5>
<button type="button" class="btn btn-outline-dark btn-circle" data-dismiss="modal" aria-label="Close">
<i class="fa fa-close"></i>
</button>
</div>
<form asp-controller="Validations" asp-action="ValidationParResponsable" asp-route-id="@Model.FicheId" asp-route-eId="@Model.EnseignantId">
<div class="modal-body">
<div class="form-group">
<input type="hidden" id="ficheId" asp-for="FicheId" />
<input type="hidden" asp-for="EnseignantId" />
<input type="hidden" asp-for="EtatId" />
<label class="control-label font-weight-bold">Commentaire :</label>
<textarea class="form-control" id="inputCommentaire" asp-for="Commentaire" placeholder="Votre commentaire"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" id="buttonRefusFiche">Refuser</button>
<button type="submit" class="btn btn-success">Valider</button>
</div>
</form>
我希望它是可以理解的,謝謝你的回復。 :)
當您使用 POST 請求時,您必須在請求正文中發送參數,而不是像這樣在 URL 中發送參數:
$("#buttonRefusFiche").click(function (e) {
ficheId = $("#ficheId").val();
commentaire = $("#inputCommentaire").val();
$.ajax({
url: "/Validations/ValidationRefuse",
type: 'POST',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType : "html",
data : {
ficheId : ficheId,
commentaire : commentaire
},
cache: true,
success: function () {
alert("Validation refusée.");
},
error: function () {
}
})
});
我還更改了 contentType 並添加了 dataType。
有關 ajax 發布的更多信息,請參閱文檔
我解決了這個問題,我只需要從我的 controller 中刪除[ValidateAntiForgeryToken]並直接在 Ajax 的正文中傳遞數據,而不是 url
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.