gpt4 book ai didi

asp.net - MVC JSON 操作返回 bool

转载 作者:行者123 更新时间:2023-12-03 22:30:49 24 4
gpt4 key购买 nike

我的 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 中),但我有点不喜欢它。

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

最佳答案

我会使用匿名对象(记住 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 属性是 bool 值,.NET 命名约定将调用它 IsCalculateTax

关于asp.net - MVC JSON 操作返回 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3754324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com