Cannot access properties of model in javascript

2019-08-06 04:12发布

问题:

I have tried a few suggestions on here however did not seem to work, I cannot seem to access the properties of the model. This is what I have so far

var widgetModel = '@Html.Raw(Json.Encode(Model.widgets))';
                [].forEach.call(widgetModel, function (widget) {
                    var template = document.querySelector('#panel-template');
                    var panelTitle = template.querySelector('.panel-title');
                    panelTitle.textContent = widget.WidgetName;
                });

Here is the rendered widgetmodel http://gyazo.com/4a960969d9bedbd71efb1dac9b99c7e6

I have also tried to access it like this, however there doesn't seem to be any properties hanging off the widget variable.

for (var i = 0; i < widgetCount; i++) {
                        var widget = widget[i];
                        var template = document.querySelector('#panel-template');
                        var panelTitle = template.querySelector('.panel-title');
                        panelTitle.textContent = widget.WidgetName;
                    }

回答1:

Mixing javascript and Razor requires that you surround your Razor call with any code block

@{ ... } or @if(condition){}, etc.

and putting the code itself in an escaped sequence

@: or the <text> tag.

So, knowing this, you can do something like

@{
        <text>
            var widgetModel = '@Html.Raw(Json.Encode(Model.widgets))';
        </text>
     }

See Mix Razor and Javascript code and Using Razor within JavaScript