Click ActionLink on view, controller checks condition, returns JSON, JQuery Ajax doesn't work.
Click the "Delete" ActionLink, "Delete" controller if customer's "Orders" property is null, if not null, a message will be popped up. If null, process to "Delete" view.
Here are the codes:
1, on the view, the @Html
and <script>
are together in a loop which goes through all the customers.
@Html.ActionLink("Delete", "Delete", new { id = item.CustomerId }, htmlAttributes: new { @class = "mergo-actionlink", id = "customer-delete-ajax" })
<script type="text/javascript">
$('#customer-delete-ajax').click(
function doSomething() {
$.ajax({
dataType: "json",
url: '@Url.Action("Delete", "Controllers", new { id = item.CustomerId })',
success: function (data) {
alert(data.message);
},
async: false
});
}
);
</script>
2, the "Delete" controller
public ActionResult Delete(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
if (customer.Orders.ToList().Count() != 0)
{
return Json(new { message = "This customer has order(s) attached." }, "text/plain", JsonRequestBehavior.AllowGet);
}
return View(customer);
}