gpt4 book ai didi

javascript - 仅在 javascript 中使用返回值

转载 作者:行者123 更新时间:2023-11-30 17:43:24 25 4
gpt4 key购买 nike

我的 Controller Address 中有一个操作 Map。在 Action Method 中,我得到了所有这样的地址:

public ActionResult Map()
{
var model = this.UnitOfWork.AddressRepository.Get();
return View(model);
}

我的地址模型如下所示:

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; }
}

现在我想在页面的 javascript 部分使用纬度和经度。我该怎么做?

我试过以下方法:

<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>

但是我得到了这个错误:

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Address_F9A550E3CE9AB1122FFC2E0A154FBDCAF8648B6FBCF91A81E35459DCA2E075AA'.

最佳答案

就像它说你在你的模式某处有一个循环引用,但你可以设置 json 解析器选项以避免循环引用。

更好的做法是将您的模式解析为单独的 View 模型:

var model = this.UnitOfWork.AddressRepository.Get().Select(m => new ViewModel{
Latitude = m.Latitude,
Longitude = m.Longitude,
});
return View(model);

这样您就可以只向需要的客户公开信息。

如果你只需要几个参数,你可能会更好地使用这样的东西:

<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>

关于javascript - 仅在 javascript 中使用返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20615623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com