【问题标题】:Mvc json response check for true/falseMvc json 响应检查真/假
【发布时间】:2011-06-27 21:53:33
【问题描述】:

我需要检查“成功”是真还是假。我从操作中得到以下 json 响应:

{“成功”:真}

我如何检查它是真是假。我试过了,但它不起作用。它回来未定义

    $.post("/Admin/NewsCategory/Delete/", { id: id }, function (data) {
        alert(data.success);
        if (data.success) {
            $(this).parents('.inputBtn').remove();
        } else {
            var obj = $(this).parents('.row');
            serverError(obj, data.message);
        }
    });

【问题讨论】:

  • 我想我明白了。我正在这样做: return Json(new { success = true, message = "this is test" }, "text/html");使用“text/html”,当我删除它时它可以工作。不确定但出于某种原因 IE 需要这个??

标签: jquery asp.net asp.net-mvc asp.net-mvc-3


【解决方案1】:

您的控制器操作应如下所示:

[HttpPost]
public ActionResult Delete(int? id)
{
    // TODO: delete the corresponding entity.
    return Json(new { success = true });
}

我个人会使用 HTTP DELETE 动词,它似乎更适合删除服务器上的资源并且更 RESTful:

[HttpDelete]
public ActionResult Delete(int? id)
{
    // TODO: delete the corresponding entity.
    return Json(new { success = true, message = "" });
}

然后:

$.ajax({
    url: '@Url.Action("Delete", "NewsCategory", new { area = "Admin" })', 
    type: 'DELETE',
    data: { id: id }, 
    success: function (result) {
        if (result.success) {
            // WARNING: remember that you are in an AJAX success handler here,
            // so $(this) is probably not pointing to what you think it does 
            // In fact it points to the XHR object which is not a DOM element 
            // and probably doesn't have any parents so you might want to adapt 
            // your $(this) usage here
            $(this).parents('.inputBtn').remove();
        } else {
            var obj = $(this).parents('.row');
            serverError(obj, result.message);
        }
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 2021-04-20
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    相关资源
    最近更新 更多