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?

5
  • 2
    I believe you wish to use: return Json(SomeCollection,JsonRequestBehavior.AllowGet) in your controller. Commented Jun 10, 2013 at 23:48
  • What does your generated html look like? Commented Jun 10, 2013 at 23:55
  • Where are you getting that error? Client side or server side? Also, I assume that doCoolStuff takes a JS object? Commented Jun 11, 2013 at 0:08
  • Hey Charlino, I am getting the error client side. Commented Jun 11, 2013 at 0:21
  • 1
    See stackoverflow.com/questions/5635383/… Commented Jun 11, 2013 at 0:28

3 Answers 3

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));
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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.

1 Comment

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.

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.