Asp.net

MVC JSON 動作返回 bool

  • March 25, 2014

我的 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 值),以便返回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屬性是布爾值,.NET 命名約定將呼叫它IsCalculateTax

引用自:https://stackoverflow.com/questions/3754324