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?
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));
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>
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.