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?

4

3 回答 3

7

问题出在return View(json);

您得到了错误的函数重载View(string),即按名称获取视图的重载。尝试:

return View((object)json);

您还想要没有 HTML 编码的原始 JSON:

 doCoolStuff(@Html.Raw(@Model));
于 2013-06-11T00:24:30.063 回答
0

你尝试这种方式的动机是什么?如果您真的想返回 json,则最好在视图/页面加载后发出 ajax 请求并使用 javascript/jquery 来呈现您的 UI。这将是 KnockoutJS 的一个很好的候选者。

于 2013-06-11T03:43:03.980 回答
0

尝试:

@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>
于 2013-06-11T00:09:20.230 回答