【问题标题】:MVC JSON actions returning boolMVC JSON 动作返回 bool
【发布时间】:2011-04-14 20:04:20
【问题描述】:

我的 ASP.NET MVC 操作是这样写的:

    //
    // GET: /TaxStatements/CalculateTax/{prettyId}
    public ActionResult CalculateTax(int prettyId)
    {
        if (prettyId == 0)
            return Json(true, JsonRequestBehavior.AllowGet);

        TaxStatement selected = _repository.Load(prettyId);
        return Json(selected.calculateTax, JsonRequestBehavior.AllowGet); // calculateTax is of type bool
    }

我遇到了这个问题,因为在 jquery 函数中使用它时出现各种错误,主要是 toLowerCase() 函数失败。

所以我必须更改操作,使其返回 bool 作为字符串(在 bool 值上调用 ToString()),以便返回 truefalse(在 qoutes 中),但我有点不不喜欢。

其他人如何处理这种情况?

【问题讨论】:

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


    【解决方案1】:

    我会使用匿名对象(记住 JSON 是键/值对):

    public ActionResult CalculateTax(int prettyId)
    {
        if (prettyId == 0)
        {
            return Json(
                new { isCalculateTax = true }, 
                JsonRequestBehavior.AllowGet
            );
        }
    
        var selected = _repository.Load(prettyId);
        return Json(
            new { isCalculateTax = selected.calculateTax }, 
            JsonRequestBehavior.AllowGet
        );
    }
    

    然后:

    success: function(result) {
        if (result.isCalculateTax) {
            ...
        }
    }
    

    备注:如果selected.calculateTax 属性是布尔值,.NET 命名约定将调用它IsCalculateTax

    【讨论】:

      猜你喜欢
      • 2011-12-03
      • 2016-01-19
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多