我正在尝试创建一个应用程序,该应用程序将视图中的数据发布到我的控制器中,这可行。但是,当我尝试使用警报进行反馈(成功或错误)时,只会给我错误。
HTML:
<!--ALERTS-->
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>API has been added!</strong>
</div>
<div class="alert alert-danger" id="danger-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>API has not been added!</strong>
</div>
<!--ALERTS-->
jQuery:
$(document).ready(function () {
$("#success-alert").hide();
$("#danger-alert").hide();
$("#btnSubmit").click(function () {
var datastring = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/ApiBroker/AddApi",
dataType: 'json',
data: datastring,
success:
function () {
$("#success-alert").fadeTo(2000, 500).slideUp(500, function () {
$("#success-alert").slideUp(500);
});
},
error:
function () {
$("#danger-alert").fadeTo(2000, 500).slideUp(500, function () {
$("#danger-alert").slideUp(500);
});
}
});
$('#myModal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
})
})
控制器:
[HttpPost]
public ActionResult AddApi(ApiRedirect model)
{
var data = model;
try
{
List<ApiRedirect> list = dbProducts.ApiRedirects.ToList();
int companyID = dbProducts.Companies.Where(x => x.CompanyName == model.Company.CompanyName).FirstOrDefault().CompanyID;
int mappingID = dbProducts.MappingNames.Where(x => x.Name == model.MappingName.Name).FirstOrDefault().MappingID;
ApiRedirect api = new ApiRedirect();
api.ApiName = model.ApiName;
api.CompanyID = companyID;
api.ApiURL2 = model.ApiURL2;
api.MappingID = mappingID;
api.ResponseType = model.ResponseType;
dbProducts.ApiRedirects.Add(api);
dbProducts.SaveChanges();
return new HttpStatusCodeResult(200);
}
catch (Exception ex){
throw ex;
}
}
我的控制器将数据插入数据库中,并且我在控制器中返回状态码200。但是,在我的JQuery中处理了错误而不是成功。
发布数据时的输出:
更新
当我在JQuery中使用console.log(data)时,我得到以下输出:
有人有什么建议吗?
谢谢!
答案 0 :(得分:0)
更改方法
[HttpPost]
public JsonResult AddApi(string value)
{
try
{
return Json("OK");
}
catch (Exception ex)
{
throw ex;
}
}
或以下(如果使用ActionResult的话)
[HttpPost]
public ActionResult AddApi(string value)
{
try
{
return Json(new {value = "complete"});
}
catch (Exception ex)
{
throw ex;
}
}
如果将以下内容添加到ajax错误中,您将能够看到错误
function(xhr, status) {
alert(status);
}