如何解决如何使用 Ajax 显示来自 BadRequest(message) 的字符串消息
我有我的 API 控制器
public ActionResult<Campaigns> AddCampaign([Bind("Name,Venue,AssignedTo,StartedOn,CompletedOn")] Campaigns campaigns)
{
try
{
if (ModelState.IsValid)
{
if (CampaignNameExists(campaigns.Name))
{
throw new Exception("A campaign with that name already exists!");
}
if(!UsersIdExists(campaigns.AssignedTo))
{
throw new Exception("User assigned to this Campaign does not exist!");
}
var isAdmin = _accessCheck.AdminCheck(campaigns.AssignedTo);
//Check if user is Admin
if(isAdmin.IsAdmin == 1)
{
throw new Exception("Admins cannot be assigned to campaigns");
}
//Send User details to Repo for insertion to DB
if (condition)
return result
else
throw new Exception("Could not add campaign");
}
else
{
throw new Exception("Model State is not valid");
}
}
catch (Exception ex)
{
var message = ex.Message;
return BadRequest(message);
}
}
和我的观点
<script>
$(document).ready(function () {
$("#createBtn").click(function () {
let data = {
"Name": $('#Name').val(),"Venue": $('#Venue').val(),"AssignedTo": $('#AssignedTo').val(),"StartedOn": $('#StartedOn').val(),"CompletedOn": $('#CompletedOn').val()
};
$.ajax({
type: "POST",url: "http://localhost:25733/api/Admin/Campaign/Add",data: JSON.stringify(data),contentType: "application/json",success: function () {
document.getElementById("campDivSuccess").style.display = 'block'
},error: function (response) {
document.getElementById("campDivFail").style.display = 'block'
let fail = '<p>'+ response +'</p>'
$('#campDivFail').append(fail);
}
})
})
})
</script>
应该在这个 div 中添加 BadRequest(string) 作为 Paragraph 标签
<div class="alert alert-dismissible alert-danger" id="campDivFail" style="display: none">
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
它正在做什么,但作为 [object] [Object] 而不是作为我分配给 BadRequest 的字符串,比如说“无法分配活动”。我搜索了很多,但找不到解决方案。我使用响应错误吗?有没有其他功能可以做到这一点?
解决方法
我找到了正确的文档。我在“response”中寻找的内容是“responseText”。我只需要在段落中使用 response.responseText 。来源:developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。