Tamer Abdulghani Tamer Abdulghani - 4 months ago 14
Javascript Question

getting two lists of objects from controller to view using json and javascript

I have drop-down list in View, when on-change I need to invoke method in the controller by javascript code, this method must return two lists of objects by using JsonResult, and deal with the results in the view in JavaScript.

Here is my View:

Files:

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

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


JavaScript Code:

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


and the method in 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);
}


So how to solve this problem??
I need your help

Answer

you can return composed object:

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