kformeck
kformeck

Reputation: 1923

ASP.NET: Illegal character '@' in '@Html.Raw' call

At one point, I had no problem collecting the raw model by calling:

@Html.Raw(Json.Encode(Model));

but now I'm getting this error:

Uncaught SyntaxError: Unexpected toke ILLEGAL

in Chrome and IE and it's point right at that '@' character

I've this (as suggested in another stackoverflow post):

var getRawLayoutData = function() { return @Html.Raw(Json.Encode(Model)); }
var rawModelData = getRawLayoutData();

and this (also suggested in another stackoverflow post):

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

and nothing seems to work.

All I want to do is pass back some modified model data from the server to the client so I can react to the changing model data.

Any suggestions??

Upvotes: 1

Views: 1743

Answers (3)

JamieD77
JamieD77

Reputation: 13949

You could always try moving your script out of the .js file and putting it into a partial view.

use dynamic as your model type and make your partial view code something like this.

@model dynamic
<script type="text/javascript">
    var getRawLayoutData = function() { return @Html.Raw(Json.Encode(Model)); }
    var rawModelData = getRawLayoutData();
</script>

Then, where you're loading your javascript file in your main view, just use this instead

@Html.Partial("_Scipt", Model)

Upvotes: 2

Chris Pratt
Chris Pratt

Reputation: 239400

Razor code only works in cshtml or vbhtml files. JS files are not preprocessed by Razor. Therefore, you were just sending the Razor code directly to the browser as JS (invalid JS). Short of just dumping all the JS code to the view, you can merely set the variable in view and then access it in your external JS file. I suggest using a namespace, though, so you don't pollute the global namespace and risk collisions with other JavaScript code.

View

<script>
    var MyNamespace = MyNamespace || {};
    MyNamespace.RawModelData = @Html.Raw(Json.Encode(Model));
</script>
<script src="/path/to/external.js"></script>

Then, in your external JS, you can reference MyNamespace.RawModelData as needed.

Upvotes: 2

jgabb
jgabb

Reputation: 554

Try changing it to @(Html.Raw(Json.Encode(Model))); instead. That should fix your problem. Looking back at my projects, this is the syntax I use and it doesn't give me any problems.

Upvotes: 0

Related Questions