javascript literals from C# - avoiding warnings

949 Views Asked by At

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.

3

There are 3 best solutions below

0
On

'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() {

        var contentListingModel = new ContentListingModel('@Html.Raw(data)');
        ko.applyBindings(contentListingModel, $('#pageRoot').get(0));

    });
0
On

The IDE is smart enough to accept lines which consist purely of Razor, so you can write:

@Html.Raw( "var data= " + Json.Encode(Model) + ";" )
alert(data);

If the (assumed) implicit global bothers you (e.g. it triggers a Resharper warning), split the declaration and assignment.

var data; // javascript
@Html.Raw( "data= " + Json.Encode(Model) + ";" ) // all razor

Which produces at runtime:

var data;
data = {"foo": "bar"};
0
On

the javascript debugger ignore the razor code and see this

var data = ;

which is a syntax error, replace this

var data = @Html.Raw(Json.Encode(Model));

with this, and the warning will be gone.

var data @('=') @Html.Raw(Json.Encode(Model));