1

I have some C# class. I want to convert to Json. But when I convert via

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

I get error in javascript

Uncaught SyntaxError: Unexpected identifier

I see this string in Firebug:

[{"Id":102,"Date":"\/Date(1419454800000)\/","Value":286890,"ListOfMetaL_Id":3,"ListOfMetal":null}]";

any ideas? Class c# for Serializer

public partial class PriceOfMetal
{
    public int Id { get; set; }
    public System.DateTime Date { get; set; }
    public double Value { get; set; }
    public int ListOfMetaL_Id { get; set; }

    public virtual ListOfMetal ListOfMetal { get; set; }
}

Controller:

public ActionResult Graph()
{
    int id = (int)TempData.Peek("id");
    string time = TempData.Peek("date").ToString();
    DateTime data = DateTime.ParseExact(time, "d", CultureInfo.InvariantCulture);
    var result = _access.GetPrice(id, data);
    ViewBag.Json = new JavaScriptSerializer().Serialize(result));
    return View(result);
}
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Denis
  • 141
  • 3
  • 14
  • No ideas. You should post some more code about it especially the `some class` - I guess nobody here is a clairvoyant. – t3chb0t Dec 25 '14 at 12:32
  • I think this might answer your question too: [JavaScriptSerializer UTC DateTime issues](http://stackoverflow.com/questions/17069460/javascriptserializer-utc-datetime-issues) - I'm pretty sure it's an issue with the date. – t3chb0t Dec 25 '14 at 12:57

1 Answers1

0

To fix the problem you could use newtonSoft, which is a Json framework.

1 - Install the package in your Visual Studio project using the Package manager console:

PM> Install-Package Newtonsoft.Json

2 - replace your line @Html.Raw(Json.Encode(@Model)) by

var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));

Now you have the javascript object serialized in model variable. You can access to you model.

I hope it helps.

Fermín
  • 737
  • 1
  • 7
  • 25