我有一个folliwng脚本实际上对两个单独的动作方法进行两次调用,并更新相关字段: -
<script type="text/javascript">
$(document).ready(function () {
$("#Switch_RackID").change(function () {
var idRack = $(this).val();
$.getJSON("/Switch/LoadDataCenterByRack", { id: idRack },
function (RackData) {
var select = $("#Switch_TMSRack_DataCenter_Name");
select.empty();
$("#Switch_TMSRack_DataCenter_Name").val(RackData.Text);
});
$.getJSON("/Switch/LoadZoneByRack", { id: idRack },
function (RackData2) {
var select = $("#Switch_TMSRack_Zone_Name");
select.empty();
$("#Switch_TMSRack_Zone_Name").val(RackData2.Text);
});
});
});
</script>
但我的问题是天气我可以使用getjson进行一次调用而不是进行两次调用,然后更新相关字段?我的行动方法如下: -
public JsonResult LoadDataCenterByRack(int id)
{
string datacentername = repository.FindRack(id).DataCenter.Name;
var DCData = new { Text = datacentername, Value = datacentername };
return Json(DCData, JsonRequestBehavior.AllowGet);
}
public JsonResult LoadZoneByRack(int id)
{
string zonername = repository.FindRack(id).Zone.Name;
var ZData = new { Text = zonername, Value = zonername };
return Json(ZData, JsonRequestBehavior.AllowGet);
}
有人可以提出建议吗? 感谢
答案 0 :(得分:0)
当然可以。您可以返回Anonymous object
将控制器操作更改为
public JsonResult LoadDataCenterByRack(int id)
{
string datacentername = repository.FindRack(id).DataCenter.Name;
var DCData = new { Text = datacentername, Value = datacentername };
string zonername = repository.FindRack(id).Zone.Name;
var ZData = new { Text = zonername, Value = zonername };
return Json(new {
DCData,
ZData
}, JsonRequestBehavior.AllowGet);
}
的JavaScript
$.getJSON("/Switch/LoadDataCenterByRack", { id: idRack },
function (response) {
$("#Switch_TMSRack_DataCenter_Name").val(response.DCData.Text);
$("#Switch_TMSRack_Zone_Name").val(response.ZData.Text);
});
您可以在JavaScript中使用console.log
来检查您获得的回复,例如
console.log(response)