单击actionlink视图,控制器检查条件,返回JSON,jQuery Ajax不起作用

时间:2015-06-01 19:29:19

标签: ajax json controller asp.net-mvc-5 actionlink

单击视图上的ActionLink,控制器检查条件,返回JSON,JQuery Ajax不起作用。

如果客户的“订单”属性为空,则单击“删除”ActionLink,“删除”控制器,如果不为空,则会弹出一条消息。如果为null,则处理为“删除”视图。

以下是代码:

1,在视图中,@Html<script>在一个循环中,通过所有客户。

@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,“删除”控制器

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);
}

1 个答案:

答案 0 :(得分:1)

你的问题不容易解释,但至于&#34; Ajax不起作用&#34;

  1. 您声明&#34; @Html<script>在一个循环中,通过所有客户&#34; 。这将是第一个错误,因为这将使用相同的Id创建许多元素,并且Id必须是唯一的。尝试使用类名作为触发器(例如下面的例子)。

  2. JavaScript不应该是该循环的一部分。没有必要循环这个脚本 - 如果它有任何损害。将它移到循环之外,并尝试使用类作为触发器,如上所述(下面的示例)。

  3. 您的ActionLinkclick事件都将使用相同的参数同时调用相同的Action。我不确定我理解你对此的期望是什么,但我假设ActionLink根本不应该调用Action。

  4. 要解决上述问题,请按照以下步骤操作,然后尝试使用此代码:

    // loop begins
    @Html.ActionLink("Delete", "Delete", new { id = item.CustomerId }, htmlAttributes: new { @class = "mergo-actionlink", data_value = item.CustomerId })
    // loop ends
    
    <script type="text/javascript">
    $('.mergo-actionlink').click(function() {
        var clickedId = $(this).attr('data-value');
        $.ajax({
            dataType: "json",
            url: '@Url.Action("Delete", "Controllers")',
            data: { id: clickedId },
            success: function (data) {
                alert(data.message);
            },
            async: false
        });
        return false;
    }); 
    </script>
    
    1. 在您的控制器中,注释掉return View(customer);。实际上,Action应该返回的唯一内容是 json ,因为这是你的Ajax唯一接受的东西。您可以将退货类型更改为JsonResult以明确。