C # javascript literals - avoiding warnings

Firstly, this code does work, but it gives me a low level of annoyance that I would like to get rid of. I have a .cshtml page that is built using razor syntax. There is a large, nasty, knockout object living behind the curtains to which many things on the page are tied. Currently, when creating an instance of this knockout model, I do this by serializing the C # model object in question in a string literal, as shown 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> 

As I said, the code works. However, on the line with a call to @ Html.Raw, I get a warning. Visual Studio believes that there is a syntax error (no, after its visualization). Now, this is perfectly reasonable WHY the thing believes that there is a syntax problem. But I would like to get rid of the warning by coding in such a way that it does not cause this problem (I understand that I could hide the warning or do any number of other things), but I just want it not to appear in cases where I serialize C # objects in JSON and type them in javascript on the page. Any ideas?

I completely agree that it is pedantic and petty to ask about it, as the code works fine and seems to be clean, but it annoys me.

+4
source share
3 answers

The IDE is smart enough to accept strings consisting solely of Razor, so you can write:

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

If the (alleged) implicit global bothers you (for example, it triggers a Resharper warning), separate the declaration and the destination.

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

What produces at runtime:

 var data; data = {"foo": "bar"}; 
+1
source

'You can just serialize your model for Json in your ActionMethod and pass it in your opinion via ViewData or ViewBag and just pass it to ViewModel using 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
source

javascript debugger ignores razor code and sees this

 var data = ; 

which is a syntax error, replace this

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

with this, and there will be no warning.

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

Source: https://habr.com/ru/post/1500056/


All Articles