1

I am trying to find the cleanest way to pass a object (recordset list) from the MVC 4 Controller to the View as a Json object.

Controller:

    var mem = BLL.Presenters.Account.GetAll().ToList();
    return View(mem);

View:

<script type="text/javascript">
    // Load data from view 
    var globalData = @(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)))
</script>

The javascript object has globalData which contains JSON.

Looking at the View, I am calling the Newtonsoft.Json.JsonConvert.SerializeObject, which I rather have in the Controller.

When I move the JsonConvert.SerializeObject to the Contoller:

   var mem = BLL.Presenters.Account.GetAll().ToList();
   var json = Newtonsoft.Json.JsonConvert.SerializeObject(mem);
   return View(json);

I get the error: Illegal characters in path.

How can I pass along a json object (already Serialize) from the Controller to the View using Newtonsoft.Json ?

1
  • I'd say your first approach is actually fine and more flexible e.g. if you ever added more data. Commented May 7, 2014 at 15:16

2 Answers 2

4

The compiler is misinterpretting your json (string) model as the name of a view and invoking the wrong overload of View. If you cast the model to object, you should be good to go:

return View((object)json)
Sign up to request clarification or add additional context in comments.

Comments

1

return View(json); is actually calling method View(string viewName).

You need to put the json to the ViewData/ViewBag or ViewModel.

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.