Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor syntax error serializing ASP.NET Model to JSON with Html.Raw

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>
like image 489
Tom Studee Avatar asked Jul 12 '13 14:07

Tom Studee


4 Answers

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)); }();
like image 132
Andrei Avatar answered Jan 02 '23 18:01

Andrei


Try to wrap it within a function as follows:

var data = function() { return @Html.Raw(Json.Encode(Model)); }();
like image 34
haim770 Avatar answered Jan 02 '23 19:01

haim770


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)); }();
like image 36
Rich Bennema Avatar answered Jan 02 '23 19:01

Rich Bennema


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.

like image 27
Chad Kuehn Avatar answered Jan 02 '23 19:01

Chad Kuehn