1

I'm trying to send data from Entity Framework database to js script on my webpage. This is my MVC Controller:

public ActionResult Index()
    {

        var wordsToShow = db.Words.Where(w => w.OwnerName == User.Identity.Name); // && DateTime.Compare(w.NextReview, DateTime.Now) <= 0

        ViewBag.wordsToShow = HttpUtility.HtmlDecode(new JavaScriptSerializer().Serialize(wordsToShow));

        var test = ViewBag.wordsToShow;


        return View();
    }

And in index.cshtml I've put this code:

<script>
    var wordsJson = "@ViewBag.wordsToShow.ToString()";
    var wordsAsObject = JSON.parse(wordsJson);
</script>

The problem is, javascript says:

Invalid character

In the line where I'm parsing json to javascript object. The reason is: json string doesn't look like it should. This is part of what's inside "wordsJson" variable in web browser:

enter image description here

What can I do to make it work?

Piotrek
  • 10,919
  • 18
  • 73
  • 136

2 Answers2

3

You're going about in an overly roundabout way. JSON is called "JavaScript Object Notation" for a reason. There's no need to put it in a string and re-parse it. You can just use the JSON as JavaScript.

ASP.NET MVC has a helper for serializing values as JSON, so you can just use that and assign it to a variable in your JavaScript:

<script>
    var wordsAsObject = @Html.Raw(Json.Encode(ViewBag.wordsToShow));
</script>

This would eliminate the need to do the JSON serialization within your Action.

I suspect that the reason you're encountering this issue is that by default, values inserted into a view with @ are automatically HTML encoded. You can use Html.Raw() to prevent this, as I've done above, but as I said, there's no reason to put it into a string first and parse it.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

I always create Method that return JsonResult/string like:

 public string GetData()
        {
         //your logic here

            string json_sales = JsonConvert.SerializeObject(<<your data>>);
            return json_sales;     
        }

and in JavaScript I just do AJAX request:

$.ajax({
        url: 'PUT_YOUR_URL_HERE_To_METHOD_GetData',
        dataType: "json",
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ Make: maka.value }),
        async: true, // Or false           
        cache: false,
        success: function (data) {
           //do something
            }

        },
        error: function (xhr) {
            alert('error');
        }
    })
David Abaev
  • 690
  • 5
  • 22