26

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
44.9k39 gold badges163 silver badges228 bronze badges
asked Jul 12, 2013 at 14:27
4
  • Is "Model" a class/namespace as well as an instance of something? Commented Jul 12, 2013 at 14:30
  • @Tom, can you post more context (e.g. the two~three lines that occur before and after that code)? Commented Jul 12, 2013 at 14:35
  • Updated the question to provide a bit more context. Commented Jul 12, 2013 at 14:40
  • although it say systax error but still work. i think it is error of VS. If you want nice compile. you can wrap it in 1 function like Andrei say bellow Commented Jul 1, 2014 at 6:19

5 Answers 5

29

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)); }();
answered Jul 12, 2013 at 14:32

3 Comments

@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 = ;.
When you wrap @Html.Raw(...) into something like [...] or func(...) it works good. Intellisense think that you are passing something into..
i would recommend var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(model)); as Json.Encode has some issues you may get Unexpected token error
18

Try to wrap it within a function as follows:

var data = function() { return @Html.Raw(Json.Encode(Model)); }();
answered Jul 14, 2013 at 20:44

Comments

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)); }();
answered Jul 26, 2014 at 16:57

1 Comment

worked good for me, but Json.Encode(model) throws the error Unexpected Token for same data.
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.

answered Aug 6, 2014 at 16:10

1 Comment

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<UserRoles> 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."
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

answered Mar 6, 2016 at 16:40

3 Comments

Actually, you don't even need the wrapping parentheses. I got something similar to work with just @Html.Raw(Json.Encode(Model))
@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.
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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.