Change the shape of the data you're returning:
[HttpPost]
public JsonResult AddNewEvent(Event e)
{
try
{
using(EventsDBEntities db = new EventsDBEntities())
{
if (db.Events.Any(x => x.Title == e.Title))
{
return Json(new { data = e, success = false, error = "This order number already exists, please check it and try again" }, JsonRequestBehavior.AllowGet);
}
db.Events.Add(e);
db.SaveChanges();
return Json(new { data = e, success = true }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json(new { data = e, success = false, error = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
Then update your Javascript to use the new data:
function Add() {
$.ajax({
type: "POST",
url: "/Home/AddNewEvent",
dataType: "JSON",
data: {
Title: $('#txtTitle').val(),
Description: $('#txtDesc').val(),
Location: $('#txtLoc').val(),
color: $('#colorAdd').val(),
fullDescription: $('#txtFullDesc').val(),
Address: $('#txtAddress').val(),
Contact: $('#txtContact').val()
},
success: function (result) {
if (!result.success) {
alert(result.error);
return;
}
$('#UpdatePanel').load(loadData());
$('#txtTitle').val("");
$('#txtDesc').val("");
$('#txtLoc').val("");
$('#colorAdd').val("");
$('#txtFullDesc').val("");
$('#txtAddress').val("");
$('#txtContact').val("");
},
error: function () {
alert("Failed! Please try again.");
}
});
}
If you want to display the error message somewhere in your form, rather than displaying an alert, change the
alert(result.error)
line to update the contents of the target element:
if (!result.success) {
$("your-target-element-selector").text(result.error);
return;
}