First off, this code does work, but it gives me a low level of annoyance that I'd like to be rid of. I have a .cshtml page that is built using the razor syntax. There is a big, nasty, knockout object living behind the scenes to which many things on the page are bound. Currently, when instantiating that knockout model, I'm doing so by serializing the C# viewmodel object in question within a string literal like below.
<script type="text/javascript">
$(document).ready(function() {
var data = @Html.Raw(Json.Encode(Model));
var contentListingModel = new ContentListingModel(data);
ko.applyBindings(contentListingModel, $('#pageRoot').get(0));
});
</script>
Like I said, the code works. However, on the line with the @Html.Raw call, I get a warning. Visual Studio believes there is a syntax error there (there isn't, after it is rendered). Now, it totally makes sense WHY the thing believes there is a syntax problem there. But I would love to get rid of the warning by coding in a way that doesn't trigger this issue (I realize I could hide the warning or do any number of other things), but I just want it to not show in cases where I'm serializing C# objects into JSON and stuffing them into javascript on the page. Any ideas?
I accept fully that it is pedantic and petty to ask about this one, since the code works perfectly well and is seemingly clean, but it annoys me.
'You Can Just Serialize Your Model To Json In Your ActionMethod , And Pass It To Your View Through ViewData Or ViewBag And Simply Pass It To ViewModel With Html.Raw , Something Like This :
//In Your ActionMethod
var serializer = new JavaScriptSerializer();
Viewdata["SomeName"] = serializer.Serialize(model);
//In Your cshtml
@{
string data = (string)Viewdata["SomeName"];
}
$(document).ready(function() {