从控制器获取两个对象列表,使用json和javascript查看

时间:2014-12-29 09:27:11

标签: c# jquery asp.net-mvc json

我在View中有下拉列表,当有变化时我需要通过javascript代码在控制器中调用方法,此方法必须使用JsonResult返回两个对象列表,并处理JavaScript中的视图结果。

这是我的观点:

Files:

    @Html.DropDownList("File", Enumerable.Empty<SelectListItem>())

<table id="trTable" class="table table-condensed table-hover table-bordered">
</table>

JavaScript代码:

<script type="text/javascript">

    $('#File').select2(
            {
                allowClear: true,
                width: 150,
            })
       .on('change', function () {
           var fileId = $('#File').val();
       $.getJSON("/Files/getWords", { fileId: fileId}, function (data) {
           $('#trTable').empty();
           var items = "<table id=" + "'trTable'" + "class=" + "'table table-condensed table-hover table-bordered'" + "'><tbody>";

          // here where I want to deal with two objects lists (Files and Words)

           });
           items += "</tbody></table>";
           $("#trTable").html(items);
       });

和Controller中的方法:

public JsonResult getWords(int fileId)
        {

           var PWs = db.Words.Where(x=>x.File_Id.Equals(fileId));
           var Files = db.Files.toList(); 

           // here where I want to pass the two lists (PWs and Files).
           //return Json(files, JsonRequestBehavior.AllowGet);
        }

那么如何解决这个问题? 我需要你的帮助

2 个答案:

答案 0 :(得分:2)

你可以返回组合对象:

var result=new { PWs=PWs, Files=Files};
return Json(result, JsonRequestBehavior.AllowGet);

答案 1 :(得分:0)

这是解决方案,控制器代码如下:

 Class ClassDetails = db.Classes.Find(clasId);
 // finding the branch of the student for registration and other fees
 int branchId = db.Students.Where(z => z.StudentID == id).Select(z => z.BranchID).FirstOrDefault();
 BranchSetting branchSettings = db.BranchSettings.Where(z => z.BranchID == branchId).FirstOrDefault();
 return Json(new { ClassDetails,branchSettings}, JsonRequestBehavior.AllowGet);

这里是jquery成功回调的代码

 success:
        function (result) {
            console.log(result);
            var classDetails = result.ClassDetails;
            var branchFee = result.branchSettings;
            if (classDetails == null || branchFee == null) {
                $("#txtMsg").html("Please contact admin.");
                $("#txtMsg").show();
                $("#Things").hide();
                $("#myModal").modal('show');

            }
            else {
                $("#txtClassName").html(classDetails.ClassName);
                $("#txtTutionFee").html(classDetails.TutionFee);
                $("#txtComputerFee").html(classDetails.ComputerFee);
                $("#txtTotalMonthlyFee").html(classDetails.TotalFee);
                $("#txtRegistrationFee").html(branchFee.RegistrationFee);
                $("#txtAddmissionFee").html(branchFee.AddmissionFee);
                $("#txtSecurityFee").html(branchFee.SecurityFee);

                $("#myModal").modal('show');
            }
        },