1

This may seem strange, but I would like to have my model contain Json data, which I could then use javascript to render html with the contents. My code looks like the following -

My Controller -

    public ActionResult Index()
    {
        Object myObject = FillMyObjectWithData();

        string json = new JavaScriptSerializer().Serialize(myObject);

        return View(json);
    }

My View -

    @model  string  /*Json data will be in the model*/
    <div>
        //standard html in here
    </div>
    <script>
        $(document).ready(function() {
            doCoolStuff(@Model);
        });          
    </script>

I am getting the error - "Illegal characters in path."

What is the correct way to accomplish this?

A Bogus
  • 3,852
  • 11
  • 39
  • 58

3 Answers3

7

The problem is in return View(json);

You are getting the wrong function overload View(string), that is the overload to get a view by name. Try:

return View((object)json);

Also you want the raw JSON without HTML encoding:

 doCoolStuff(@Html.Raw(@Model));
fcuesta
  • 4,429
  • 1
  • 18
  • 13
0

Try:

@model  string  /*Json data will be in the model*/
<div>
    //standard html in here
</div>
<script>
    $(document).ready(function() {
        var temp = @model;
        doCoolStuff(temp);
    });          
</script>
Haney
  • 32,775
  • 8
  • 59
  • 68
0

What is your motivation for attempting it this way? If you really want to return json you may be better served making an ajax request after the view/page loads and using javascript/jquery to render your UI with. This would be a good candidate for KnockoutJS.

Jacob Rutherford
  • 584
  • 3
  • 11
  • Hey Jacob, Thanks for the response. I thought about doing this the way you suggest, but then I would have to make two calls to the server. One for the View, then one for the Json data. – A Bogus Jun 12 '13 at 00:23