从控制器返回Json对象并在jquery中解析

时间:2013-12-12 12:03:41

标签: jquery json asp.net-mvc-3 parsing

控制器:

int intId = 0;
var jsonlist = new JsonResult();
for (var i = 0; i < model2.Count; i++) {
    intId = (int) model2[i].Id;
    var abc = objModel.GetSubCategories(ID, intId);
    Json(new {
            jsonlist = abc
        },
        JsonRequestBehavior.AllowGet);
}
ViewData["SubTypes"] = jsonlist;

@
ViewBag.Total = intTotal;
return View(model);
}

JS:

var myArray = new Array();
var list = ('<%: ViewData["SubTypes"] %>');
alert(list);
myArray = $.parseJSON(list);
////        var obj = new Object();
//        var obj = JSON.parse(myArray);
//        alert(obj);

警报为System.Web.MVC.JsonResult。我无法解析它。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

为什么不使用Ajax帖子并返回Json结果而不是从隐藏变量解析json结果?

**$.ajax({
        url: "/Controller/ActionName/",
        data: $('#FormId').serialize(), //Serializing the Form data here
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            if (response.success) {
                //You should be able to parse the jason result from 
                alert(response.SubTypes.ID) //Example
            }
        }
    });


    public class ResultViewModel
    {
        public IList<SubCategory> SubCategoryList { get; set; }
    }

    public class SubCategory
    {
        //Set the properties
    }


        [HttpPost]
        public JsonResult ActionName(Viewmodel model)
        {
            ResultViewModel result = new ResultViewModel();

            for (var i = 0; i < model2.Count; i++) {
                intDewCardTypeId = (int) model2[i].DewCardTypeId;
                var abc = objProductModel.GetSubCategories(ID, intDewCardTypeId);
                result.SubCategoryList.Add(abc);
            }
            return Json(new { success = true, ErrorMessage = String.Empty, SubTypes = result });
        }**