【问题标题】:Return Json object from controller and parse in jquery从控制器返回 Json 对象并在 jquery 中解析
【发布时间】:2013-12-12 12:03:41
【问题描述】:

控制器:

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。我无法解析它。

我做错了什么?

【问题讨论】:

  • 你应该使用var myArray = @Html.Raw(Json.Encode(ViewData["SubTypes"]));。 MVC默认做的时候不需要在客户端解析

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


【解决方案1】:

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

**$.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 });
        }**

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多