Domanda

So I have been looking through relevant questions and I can't figure out exactly why my script tag is malformed.

<script language="javascript" type="text/javascript">
    var showME = false;
    var showSuffix = "";

    @if (ViewData["showME"] != null && ViewData["showSuffix"] != null)
    {
        <text>
        showME = @(Convert.ToBoolean(ViewData["showME"]) ? "true" : "false");
        showSuffix = '@Html.Raw(Json.Encode(ViewData["showSuffix "]))';
        </text>
    }
</script>

EDIT! The answer below is correct but I tracked down the malformed part to this line.

var videoHelpUrl = @(Url.Action("Index", "Help", new { Id = 46 }));
È stato utile?

Soluzione

Try this:

<script language="javascript" type="text/javascript">
    var videoHelpUrl = '@Url.Action("Index", "Help", new { Id = 46 })';
    console.log(videoHelpUrl);
</script>

console.log will output the Url.

Note: Always keep in mind that everything following @ in a Razor view will be processed by the Razor engine. This is why you can surround @Url.Action(...) with quotes. It will be processed first by Razor engine and then by Javascript when it is executed.

Altri suggerimenti

If you try using double {{ }} as in;

@{

    if (ViewData["showME"] != null && ViewData["showSuffix"] != null)
    {
        <text>
        showME = @(Convert.ToBoolean(ViewData["showME"]) ? "true" : "false");
        showSuffix = '@Html.Raw(Json.Encode(ViewData["showSuffix "]))';        
        </text>
    }

}

See if that works.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top