Reputation: 6820
I have an action Map in my Controller Address. In the Action Method I get all the addresses like this:
public ActionResult Map()
{
var model = this.UnitOfWork.AddressRepository.Get();
return View(model);
}
My Address Model looks like this:
public class Address
{
public Int32 Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public Decimal Latitude { get; set; }
public Decimal Longitude { get; set; }
public Int32 StreetNumber { get; set; }
public Int32 RegionId { get; set; }
public virtual Region Region { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
Now I would like to use the latitude and the longitude in the javascript part of the page. How can I do this?
I've tried to the following:
<script>
var model = @Html.Raw(Json.Encode(Model));
// at this stage the model javascript variable represents the JSON encoded
// value of your server side model so that you can access all it's properties:
alert(model.length);
</script>
But I got this error:
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Address_F9A550E3CE9AB1122FFC2E0A154FBDCAF8648B6FBCF91A81E35459DCA2E075AA'.
Upvotes: 1
Views: 303
Reputation: 2384
Like it says you have a circular reference somewhere in your mode, but you can set the json parser with options to avoid circular references.
Better would be to parse your mode into a separate viewmodel:
var model = this.UnitOfWork.AddressRepository.Get().Select(m => new ViewModel{
Latitude = m.Latitude,
Longitude = m.Longitude,
});
return View(model);
This way you only expose the information to the client that is needed.
If you need only a few parameters you might be better of with something like this:
<script>
var lat = @Model.Latitude;
var lon = @Model.Longitude;
// at this stage the model javascript variable represents the JSON encoded
// value of your server side model so that you can access all it's properties:
alert(lat);
</script>
Upvotes: 2