在ASP.net函数中获取JsonResult

时间:2011-01-31 19:58:36

标签: asp.net json asp.net-mvc-2

如何获取返回JsonResult并强制转换为字符串的方法的结果。

 [HttpPost]
        public JsonResult AnalyseNbPayment(DateTime dt, DateTime dt2,int FrequencyID) {

            if (FrequencyID == ApplConfig.Frequency.WEEKLY) {
                return Json(new  { val = GetNbWeek(dt, dt2) });
            }
            else if (FrequencyID == ApplConfig.Frequency.MONTHLY) {
                return Json(new  { val =GetDateDiffInMonth(dt, dt2) });
            }
            else if (FrequencyID == ApplConfig.Frequency.QUARTELY) {
                   return Json(new  { val = GetQuarterLy(dt, dt2) });
            }
            else if (FrequencyID == ApplConfig.Frequency.BI_MONTLY) {
               return Json(new  { val = GetBiMontlhy(dt, dt2) });
            }
            else if(FrequencyID == ApplConfig.Frequency.YEARLY)
            {
                return Json(new { val = GetNbYear(dt, dt2) });
            }

            return Json(new { val =0 });
        }

我想这样称呼我的方法

string MyValue = AnalyseNbPayment(Convert.ToDateTime(ViewModel.oRent.DateFrom), Convert.ToDateTime(ViewModel.oRent.DateTo), Convert.ToInt32(oLease.FrequencyID)).val.ToString(); <br />

由于

2 个答案:

答案 0 :(得分:2)

试试这个:

var jsonResult = AnalyseNbPayment();
var json = new JavaScriptSerializer().Serialize(jsonResult.Data);

答案 1 :(得分:0)

另一种选择是使用dynamic类型来检索信息。在你的情况下,它将是(确保在赋值结束时有.Data):

dynamic MyValue = AnalyseNbPayment(Convert.ToDateTime(ViewModel.oRent.DateFrom), Convert.ToDateTime(ViewModel.oRent.DateTo), Convert.ToInt32(oLease.FrequencyID)).Data;

然后您可以简单地执行以下操作:

//the var val will be the appropriate data type...in your case it looks like int so .ToString() will get you what you want.
var result = MyValue.val.ToString();

动态类型是一些疯狂的东西!