tbonejenkins
tbonejenkins

Reputation: 379

Passing view model data to javascript - Unexpected token ILLEGAL

// controller
public ActionResult Index()
{
   var viewModel = new IndexViewModel();

   viewModel.Title = "It's Alive!!";

   return View(viewModel);
} 

// view
@model Project.Models.IndexViewModel

@section Script {
    <script src="~/Scripts/scripts.js"></script>
    <script>
        var options = {
            title: @Html.Raw(Model.Title)
        }

        application.init(options);
    </script>    
}

When the page loads the following error is displayed

Uncaught SyntaxError: Unexpected identifier

The apostrophe in the string seems to be causing this issue, but i'm not sure how I would resolve this.Any help would be greatly appreciated

Upvotes: 1

Views: 1417

Answers (2)

Win
Win

Reputation: 62290

You can serialize with Newtonsoft Json before rendering.

@using Newtonsoft.Json

@section Script {
    <script src="~/Scripts/scripts.js"></script>
    <script>
        var options = {
            title: @Html.Raw(JsonConvert.SerializeObject(Model.Title))
        }

        application.init(options);
    </script>    
}

Output for Double Quote

title: "It \"s Alive!!"

Output for Single Quote

title: "It 's Alive!!"

Upvotes: 0

mojorisinify
mojorisinify

Reputation: 405

Try this:

  title: '@Html.Raw(Json.Encode(Model.Title))'

Upvotes: 2

Related Questions