25

This line is giving me a syntax error in Visual Studio 2012 (literally just 'Syntax Error'):

var data = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));

Model in this case is the instance of @model MyApp.ViewModels.MyViewModel declared at the top of my cshtml.

My model is serialized properly into the data var, and the application works correctly. Cosmetically it's just annoying to have the error permanently in my error list.

How should I modify the line so that the compiler is happy?

edit:

As requested, more context. Here's the entire $(document).ready():

<script type="text/javascript">

    $(document).ready(function () {

        $('#ReportDate').datepicker();
        $('#DispositionDate').datepicker();

        var data = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));

        var vm = new NonconformingProductViewModel(data);
        ko.applyBindingsWithValidation(vm);

        // validate on page load so all reqd fields are highlighted.
        var valid = ko.validation.group(vm, {deep: true});
        valid.showAllMessages(true);

    }); // end document.ready

</script>
Andrei
  • 42,814
  • 35
  • 154
  • 218
Tom Studee
  • 10,316
  • 4
  • 38
  • 42

5 Answers5

28

Using function

Implement a simple JavaScript set function that returns input argument:

function set(value){
    return value;
}

Use this function to assign Razor model value to a JavaScript variable:

var data = set(@Json.Encode(Model));

As an option you can use self-calling function:

var data = function() { return set(@Json.Encode(Model)); }();
Andrei
  • 42,814
  • 35
  • 154
  • 218
  • 2
    @TomStudee I guess that there is no way for JS intellisense to know what is the outcome of the @Html.Raw. As far as he's concerned, this might as well return an empty string, giving you a `var data = ;`. – Simon Belanger Jul 12 '13 at 14:55
  • 3
    When you wrap @Html.Raw(...) into something like [...] or func(...) it works good. Intellisense think that you are passing something into.. – Andrei Jul 12 '13 at 16:10
  • 1
    i would recommend `var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(model));` as `Json.Encode` has some issues you may get _Unexpected token_ error – sairfan May 01 '19 at 16:16
18

Try to wrap it within a function as follows:

var data = function() { return @Html.Raw(Json.Encode(Model)); }();
haim770
  • 48,394
  • 7
  • 105
  • 133
14

Use JSON.Net, instead of either the JavaScriptSerializer or DataContractJsonSerializer, to avoid the nightmare that is JSON Dates:

var data = function () { 
    return @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)); }();
Rich Bennema
  • 10,295
  • 4
  • 37
  • 58
8

Even easier!! This will fix that little annoyance:

var model = [@Html.Raw(Json.Encode(Model))][0];

Basically intellisense wants something around @Html.Raw. There is actually nothing wrong but we have to handle the intellisense shortcoming. Here we declare the result as the first index of a new array, then return the first index.

FYI: If you want your model to reflect changes to the DOM then try the JSModel class.

2Yootz
  • 3,971
  • 1
  • 36
  • 31
  • sometimes intellisense will make you (me) fall when you (I) are not 100% sure about how thins (razor views) works. Thanks, this should be the correct answer. In my case I have a List and it is set to a javascript object in the view using - var myJsArray = @Html.Raw(Json.Encode(@Model.SelectableUserRoleTypes)).. later in knockoutjs I set a ko.observableArray(myJsArray)... and when listening to the intellisense warning and adding quotes to the assignment "@Html..." this will produce a string instead of array, hence the ko.observable will give error "...must be an array." – JimiSweden Oct 05 '17 at 13:12
4

You don't need to write any new javascript functions, just wrap the code into brackets

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

works for me in Visual Studio 2015, not sure about VS2012

aluky
  • 491
  • 6
  • 11
  • Actually, you don't even need the wrapping parentheses. I got something similar to work with just `@Html.Raw(Json.Encode(Model))` – Alexandros Katechis Oct 03 '16 at 21:56
  • @Kindinos There's a problem with IntelliSense, it shows the message 'Syntax Error' even if the code works correctly, so we need to use the parentheses only to suppress this warning. – aluky Oct 04 '16 at 16:24
  • this is a good answer as it tells you to not worry about the intellisense, unfortunately my intellisense complains when surrounding the code with parenthesis (...) , I had to use the trick from Chad – JimiSweden Oct 05 '17 at 13:14