MVC JSON行动返回布尔 [英] MVC JSON actions returning bool

查看:124
本文介绍了MVC JSON行动返回布尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样写我的ASP.NET MVC的行动:

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
    }

我因为jQuery函数使用时有这个问题,我有各种各样的错误,主要是与toLowerCase()函数失败。

所以我不得不改变的方式行动,他们返回布尔作为字符串(调用的ToString()对布尔值),从而使大公符真正(在qoutes),但我有点不喜欢它。

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是键/值对):

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

和则:

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

注:如果 selected.calculateTax 属性是布尔的.NET命名约定将称之为 IsCalculateTax

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

这篇关于MVC JSON行动返回布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆