MVC JSON操作返回布尔(MVC JSON actions returning bool)

编程入门 行业动态 更新时间:2024-10-25 12:21:24
MVC JSON操作返回布尔(MVC JSON actions returning bool)

我有我的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作为字符串返回ToString()在bool值上调用ToString() ),以便返回true或false (在qoutes中),但我有点不喜欢它。

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

I had my ASP.NET MVC actions written like this:

// // 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 }

I had problems with this because when using it in jquery functions I had all sorts of error, mostly toLowerCase() function failing.

So I had to change the actions in a way that they return bool as string (calling ToString() on bool values), so that thay return true or false (in the qoutes) but I kinda don't like it.

How do others handle such a case?

最满意答案

我会使用匿名对象(请记住,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 。

I would use anonymous object (remember that JSON is a key/value pairs):

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

And then:

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

Remark: if the selected.calculateTax property is boolean the .NET naming convention would be to call it IsCalculateTax.

更多推荐

本文发布于:2023-04-29 04:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:布尔   操作   JSON   MVC   returning

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!