【发布时间】:2015-06-12 20:09:08
【问题描述】:
我有一个如下所示的 change/getJson 函数:
$('#CountryId').change(function () {
$.getJSON('@Url.Action("StateList", "Manage")', {id: $('#CountryId').val()}, function (data) {
var items = '<option value="">Select a State</option>';
$.each(data.List, function (i, state) {
items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
});
$('#StateId').html(items);
//Fail
//console.log(">>>>" + data.LatLng.Latitude);
//$('#Latitude').val(data.LatLng.Latitude);
//Success
//$.each(data.LatLng, function (i, country) {
// $('#Latitude').val(country.Latitude);
// console.log(">>>>" + country.Latitude);
//});
$('#CityId').html('<option value="">Select a City</option>');
});
});
数据从我的 json 结果中恢复正常。它正在返回该 CountryId 的状态列表(CountryId 是 States 表中的 FK)来构建我的选择列表/下拉列表以进行控制。它还返回 CountryId 的纬度和经度(来自国家表)。我的选择列表的状态列表很好。但是,纬度和经度将永远只是一组值(即一条记录)。我可以让它在 jquery 中工作的唯一方法是使用 .each 循环:
$.each(data.LatLng, function (i, country) {
$('#Latitude').val(country.Latitude);
console.log(">>>>" + country.Latitude);
});
我不需要循环,因为它是一组值。有没有另一种更简洁的方式来格式化它并避免额外的功能?从我上面的代码中可以看出,我已经尝试过了:
console.log(">>>>" + data.LatLng.Latitude);
$('#Latitude').val(data.LatLng.Latitude);
...还有许多其他事情,它总是会回来undefined。这是来自控制器的我的 StateList 片段:
[HttpGet]
public ActionResult StateList(int id)
{
var list = db.States.Where(d => d.CountryId == id).Select(d => new { Text = d.StateName, Value = d.StateId }).ToList();
var latlng = db.Countries.Where(d => d.CountryId == id).Select(d => new { d.Latitude, d.Longitude });
var result = new { List = list, LatLng = latlng };
return Json(result, JsonRequestBehavior.AllowGet);
}
我尝试在此 ActionResult 中格式化 latlng 数据(即 ToList、ToString、Lat = d.Latitude 等),但只要我把它放在循环中,jquery 似乎并不关心。
我可以在 Internet 上找到的所有示例都是 json 列表,它们在状态列表部分非常有效。但是,我似乎找不到任何关于单个 json 值的信息。到目前为止,您似乎必须将值分成几部分,以便 jquery 可以解释它?有人知道消除循环的诀窍吗?
【问题讨论】:
-
转储以控制 json 结果并检查
LatLng。它可能是一个数组,所以然后通过添加.Single()或.First()来调整您的查询。 -
试试:
console.log(data.LatLng[0].Latitude); -
谢谢大家,我不确定
data.LatLng[0].Latitude是否更像是一个故障排除步骤,但这两个实际上都适用于我正在尝试做的事情。我想我正在寻找.Single(),因为它看起来更干净/优雅。如果是ToSingle(),我可能自己也想通了。令我惊讶的是,我在谷歌中找不到这些东西,包括如何将所有内容转储到控制台。无论如何......@Jasen如果你想写下来,我会把你的功劳作为答案。谢谢。
标签: javascript jquery json asp.net-mvc razor