MVC4 razor accessing JsonResult data from my model in client side javascript

martin picture martin · Jul 11, 2012 · Viewed 9.9k times · Source

I am working on an MVC4 razor project. I have a list of role objects that I store on my model as a jsonResult intended to be used in my client-side javascript.

//Model
public JsonResult JsonRoles { get; set; }

//Controller
var myroles = from r in myroles select new { r.Id, r.Description };
var myModel.JsonRoles = Json(myroles);


//Client side javascript
var data = '@(Model.JsonRoles)';
alert(data);

I tried to access this in javascript as below. When I alert I always get the string "System.Web.Mvc.JsonResult" but what I need is the json data. What am I doing wrong? Can someone please point me in the right direction

Answer

Ajay Beniwal picture Ajay Beniwal · Jul 11, 2012

I have used ViewData to solve your problem and im able to get the result on the similar lines you can resolve model property also

//Contoller Class 
 public ActionResult CreateRequest()
        {

            var data = new { Id = "one", Make = "Two" };


            ViewData["Data"] = Json(data);

            return View();

        }

//And client side is 

  <script type="text/javascript">
        var data = @Html.Raw(Json.Encode(ViewData["Data"]));
        alert(JSON.stringify(data.Data));
    </script>