0

I am working with mvc 4 and jQuery. If I try it this works

var obj = new Object();
obj.name = "Raj";
obj.age  = 32;
obj.married = false;
var jsonString= JSON.stringify(obj);
alert(jsonString);

But if I try to convert to my object to JSON it does not work

var obj = new Object();
obj.name = "Raj";
obj.age  = 32;
obj.married = false;
obj.Venta=@Model;
var jsonString= JSON.stringify(obj);
alert(jsonString);

As you see I added @Model then this does not work.

I need convert this object to JSON and this would be great if there is a automatic way for get it

public class VentaProd
{
    public IEnumerable<product> ListadoProductos {get; set;}
    public IEnumerable<account> ListadoClientes { get; set; }
    public sale Venta { get; set; } 
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
angel
  • 4,474
  • 12
  • 57
  • 89

1 Answers1

0

From my experience, C# Models/variables should be enclosed within quotes when assigned to java script variables.

Try doing: obj.Venta = '@Model';

Hope this helps!

user1347295
  • 36
  • 1
  • 7
  • this runs but this prints the type of model, "ejercicio1.Models.ClasesCombinadas.VentaProd" – angel Jun 24 '15 at 17:45
  • I never came accorss this scenario but logically its worth a try. If your Model is VentaProd then I think the code should look like this: obj.Venta = '@Model.Venta'; – user1347295 Jun 24 '15 at 17:48
  • yes my Model is VentaProd then how the controller must to read it? as a string? – angel Jun 24 '15 at 17:49
  • really which i want to do is convert to json my object for read it on controller the real code would be obj='@Model' and i got \" ejercicio1.Models.ClasesCombinadas.VentaProd\" now i am not sure if i could deserializate it using JavaScriptSerializer – angel Jun 24 '15 at 18:00
  • Well converting C# object to JSON using razor can be done like this: var obj = @Html.Raw(Json.Encode(Model)); – user1347295 Jun 24 '15 at 18:05
  • i believe this could work but now i got a circular reference – angel Jun 24 '15 at 18:09
  • Here is very nice answer with example to solve circular reference problem. Assuming you are getting it in JSON.Stringify method. http://stackoverflow.com/questions/10392293/stringify-javascript-object-with-circular-reference – user1347295 Jun 24 '15 at 18:17