Search code examples
asp.net-mvcasp.net-mvc-4knockout.jsrazor-2

Problems using the Razor model when creating my knockout ViewModel


I'm having problems with using the Model in a javascript call when setting up my knockout VM..

@model List<AdminGui.Models.Domain>

<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js" type="text/javascript"></script>
<script type="text/javascript">
function ViewModel() {
    var self = this;

    self.domains = ko.observableArray(
        ko.utils.arrayMap(@Model, function(item) {
            return new Domain(item.guid, item.description, item.namespaces);
        }));
}

I get a syntax error on @Model in the ko.utils.arrayMap call. I suspect it might be my Razor-fu that is lacking... :)


Solution

  • The Model is your C# model which cannot be used directly from JavaScript, because writing @Model just calls ToString on it which is not what you need.

    What you need is to convert your Model to JSON, you can do this with the Json.Encode method

    self.domains = ko.observableArray(
            ko.utils.arrayMap(@Html.Raw(Json.Encode(Model)), function(item) {
                return new Domain(item.guid, item.description, item.namespaces);
            }));
    

    Note: You need to wrap it with Html.Raw to turn off the automatic HTML Encoding in Razor.