Reputation: 2646
This question is actually continuing/expanding my question here.
I have the model SchoolTestsPerModulePerStudent which is actually the following
public partial class SchoolTestsPerModulePerStudent
{
public long StudentID { get; set; }
public long ModuleID { get; set; }
public System.DateTime TestDate { get; set; }
public int TestResult { get; set; }
}
As I mentioned at the previous question I have this code at a function of a controller
var query = from b in db.SchoolTestsPerModulePerStudent
where b.StudentID.Equals(2)
select b;
return View(query.ToArray());
Well, now, b gets all the SchoolTestsPerModulePerStudent records for the Student with StudentID 2.
The problem I have now, is that I want to split b, in two different arrays, which I want to be used as arrays in javascript at my view.
So now I have two problems:
Is it possible to break my array containing the SchoolTestsPerModulePerStudent records to two different ones that I can return at the view? More specifically, I want the first to contain only the TestDate, while the second to contain only the TestResult. I cannot find any option I can use to create arrays only from a column of an other table...
The second is how I am able to return both these new arrays using one function only? Is it possible? Basically, what I want to avoid, is a second execution of the query (delay), and also the cases where if I execute two queries to get each one of the tables, that it is possible that there are cases where the elements will be returned to be with different order, so the two arrays will not match.
In addition in javascript, at my previous question I got answer that be returned as arrays, they should be returned as JSON like that @Json.Encode(Model)
. So I can use @Json.Encode(TestDatesArray)
and @Json.Encode(TestResultsArray)
in my case?
Upvotes: 0
Views: 297
Reputation: 12683
Jim,
By creating another model class you can do this with no problems and selecting the data from your query results to an array. Now I am assuming as you stated you only want the two properties TestDate
and TestResult
in no particular selection order without any other properties.
Model:
public partial class SchoolTestResultsModel
{
public int[] TestResults { get; set; }
public DateTime[] TestDates { get;set; }
}
Adapted Method:
var query = from b in db.SchoolTestsPerModulePerStudent
where b.StudentID.Equals(2)
select b;
var model = new SchoolTestResultsModel();
model.TestDates = query.Select(x => x.TestDate).ToArray();
model.TestResults = query.Select(x => x.TestResult).ToArray();
return View(model);
Then your JSON Encoding can be
@Json.Encode(Model.TestResults)
@Json.Encode(Model.TestDates)
Now ensure that your view is setup to use the new model.
@model SchoolTestResultsModel
Upvotes: 2