Question

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

Was it helpful?

Solution

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>

OTHER TIPS

JsonResult tends to be used as the return type of an action method you intend on calling from Ajax.

You need to use the JavaScriptSerializer to serialize your "myroles" object. E.g.

JavaScriptSerializer serializer = new JavaScriptSerializer();
myModel.JsonRoles = serializer.Serialize(myroles);

Change the type of JsonRoles on your model to string.

public string JsonRoles { get; set; }

Finally, output in your view as e.g.:

var data = @Html.Raw(Model.JsonRoles);
alert(data.id);

In linqpad, I was able to get the data back out via

var x= new System.Web.Mvc.JsonResult();
x.Data=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize("testing, testing");
x.Data.Dump();

also checked with

var x= new System.Web.Mvc.JsonResult();
x.Data=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new{test="testing"});
x.Data.Dump();

Which may not be the correct solution for in a razor page. I expect

var data = "@{Model.JsonRoles.ExecuteResult(this.ControllerContext);}";

to be correct in a proper mvc app.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top