[英]Pass message from Controller to AJAX script in View
I'm using jQuery and AJAX in the View to send some data to the Controller that writes it to the database. 我在View中使用jQuery和AJAX将一些数据发送到将其写入数据库的Controller。 On success I show a div tag with a green background with "OK" text. 成功后,我将显示带有绿色背景的div标签,并带有“确定”文本。 But what if I do a check first in the Controller if the data already exist in the database, then I would like to alert the user that the data could not be added. 但是,如果我先在Controller中检查数据库中是否已经存在数据,该怎么办,然后我想提醒用户无法添加数据。 Is there a way to pass some kind of message back to the AJAX script? 有没有办法将某种消息传递回AJAX脚本?
I guess the success option is just a confirm of contact with the Controller and not a real confirm that everything is OK and the data has been added to the database!? 我猜成功选项只是确认与Controller的联系,而不是真正确认一切正常,并且数据已添加到数据库!
What action in the Controller would cause the error function in the AJAX code to run? 控制器中的什么动作会导致AJAX代码中的错误功能运行?
Finally I just wonder what kind of return I should use since I'm actually not returning anything? 最后,我只是想知道应该使用哪种类型的退货,因为我实际上什么也没退呢?
My script in the View: 我在视图中的脚本:
$.ajax({
url: "/Orders/AddOrder",
type: "GET",
cache: false,
data: { a: order, b: seller },
success: function () {
console.log('AJAX successful');
// Show confirm message
$(".messageOk").show();
$(".messageOk").text("OK").delay(2000).queue(function () {
location.reload();
});
},
error: function () {
????
},
complete: function () {
????
}
});
Controller: 控制器:
// Add new Resource
public ActionResult AddOrder(int a, int b)
{
var order = new Order
{
OrderNumber = a,
Seller = b
};
db.Orders.Add(order);
db.SaveChanges();
//return new EmptyResult();
return RedirectToAction("Index", "Home"); // ??????
}
You could return the appropriate HTTP status code from your controller action: 409 Conflict
. 您可以从控制器操作中返回适当的HTTP状态代码: 409 Conflict
。
if (the resource already exists in db) {
return new HttpStatusCodeResult(HttpStatusCode.Conflict);
}
which will trigger the error
AJAX function in which you could check whether you are in this situation and act accordingly: 这将触发error
AJAX函数,您可以在其中检查您是否处于这种情况下并采取相应的措施:
error: function(jqXHR) {
if (jqXHR.status == 409) {
alert('Sorry but this resource already exists');
}
}
As you can see this way it's up to the view to decide what error messages to display based on proper HTTP status codes returned from the server. 如您所见,是由视图根据服务器返回的正确HTTP状态代码决定要显示的错误消息。 This way you are not cluttering the server with view logic. 这样,您就不会因视图逻辑而使服务器混乱。
除了正确的响应状态代码外,您还可以将响应主体的错误消息从服务器传递为JSON字符串或纯字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.