我有一个变化/的getJSON功能,看起来像这样:格式多单的结果的Json值
$('#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结果罚款回来。它为StateId返回一个状态列表(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);
...和许多其他的东西,它总是回来不确定。这里是从控制器我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的似乎不是只要我把照顾它在循环中。
我可以在互联网上找到的所有例子都是针对状态列表部分的json列表。但是,我似乎无法找到关于单个json值的任何信息。看来到目前为止,你必须将价值分解成碎片,以便jquery能够解释它?任何人都知道消除循环的诀窍?
转储以控制json结果并检查'LatLng'。这可能是一个数组,然后通过添加'.Single()'或'.First()'来调整查询。 – Jasen
尝试:'console.log(data.LatLng [0] .Latitude);' – Hackerman
谢谢你们,我不确定'data.LatLng [0] .Latitude'是不是故障排除步骤,但这两个实际上是为了我想要做的。我想我正在寻找'.Single()',因为它看起来更干净/优雅。如果它是'ToSingle()',我可能自己弄明白了。它令我惊讶,我无法在Google中找到这些东西,包括如何将所有内容转储到控制台。无论如何... @Jasen如果你想写出来,我会给你信用作为答案。谢谢。 – SumNone