0

我有以下脚本,它实际上对两个单独的操作方法进行了两次调用,并更新了相关字段:-

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

有人可以建议吗?谢谢

4

1 回答 1

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

console.log您可以通过在 JavaScript 中使用来检查您得到的响应,例如

console.log(response)
于 2013-10-31T13:51:13.503 回答