我的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()
),以便返回true
或false
(在qoutes中) )但我有点不喜欢它。
其他人如何处理这种情况?
答案 0 :(得分:16)
我会使用匿名对象(请记住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
。