How to return mvc5 model via an ajax call which can then be iterated with foreach( mvc5model, function(key,value){}


I need to return a model from mvc 5 controller via an ajax call, in a ObjectArray format which can be iterated as a key value pair. I've tried stringify and 'toJSON' and @HTML.raw and serializing the model on the controller side or using cast to Json on controller side, but with no luck. The viewModel passed back is an instantiated class with several properties.


public JsonResult FindPersonOn( long? IdNumber)
        // populate viewModel.Person
        // populate ViewModel.Designation

        //JavaScriptSerializer oSerializer =
                new JavaScriptSerializer();
        //string sJSON = oSerializer.Serialize(driverViewModel);
        //return Json(sJSON);

        // return Json(viewModel)


    type: "Post",
    url: "/DesignationPerson/FindPersonOn/",
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data)
        //var obj = JSON.stringify(data);           
        //var obj = $.toJSON(data)

        var obj = data;
        $.each(obj, function (key, value)
            if (key == 'person')
                // populate some html elements

Exception; Unhandled exception at line 489, column 2 in http://localhost:60667/Scripts/jquery-3.3.1.js 0x800a138f - JavaScript runtime error: Invalid operand to 'in': Object expected occurred



Usually I pass the mode from an ActionResult with return View(model) and in the view I serialize it with razor

@using System.Web.Script.Serialization
    var javaScriptSearilizer = new JavaScriptSerializer();
    var serializedPersonViewModel = javaScriptSearilizer.Serialize(Model);

and in the script on $(document).ready I get it into a local variable with serializedPersonViewModel = @Html.Raw(serializedPersonViewModel);

but in the ajax done or success, I can't get it working.


asked on Stack Overflow Sep 20, 2019 by Neal Rogers • edited Sep 20, 2019 by Neal Rogers

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0