1

Controller:

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

The alert is System.Web.MVC.JsonResult. I am not able to parse it.

What am I doing wrong?

1
  • 2
    You should use var myArray = @Html.Raw(Json.Encode(ViewData["SubTypes"]));. No need to parse it on the client-side when MVC does it by default Commented Dec 12, 2013 at 12:10

1 Answer 1

1

Why dont you use an Ajax post and return a Jason result instead of parsing the jason result from a hidden variable?

**$.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 });
        }**
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.