ASP.Net array loses structure with Javascript function - javascript

I am currently working on a ASP.Net MVC Razor application.
in my controller, I load two dictionaries with data and place them in a ViewModel as follows:
public Dictionary<String, List<String>> EngineerSchedule { get; set; }
public Dictionary<String, List<String>> WeeklySchedule { get; set; }
when in the view, I traverse the dictionaries to retrieve the List objects at every Key, I then change this String List into an Array and send them to a JavaScript function.
In my Js function, I would like to assign the above array to JS variables, when doing so, the JS variables become an array where the index holds the entire array from the function call.
Also, the params become an array of Chars
Any advice to why this happens will be greatly appreciated!
Code in View:
#foreach(var week in Model.WeeklySchedule)
{
var key = week.Key;
var values = week.Value.ToArray();
string[] eng = { };
foreach (var item in Model.EngineerSchedule)
{
if (item.Key == key)
{
eng = item.Value.ToArray();
}
}
#: gatherTimes('#Html.Raw(Json.Encode(key))', '#Html.Raw(Json.Encode(values))', '#Html.Raw(Json.Encode(eng))');
//In here, both values and engs are Array of the correct type and length
}
function gatherTimes(weekKey, values, engs)
{
var week =[];
var eng = [];
week[week.length] = values;
eng[eng.length] = engs;
for(var i = 0; i < engs.length; i++)
{
alert(engs[i]); //Outputs single chars, rather then the string values
alert(eng[i]); //Outputs an array with the length of all the chars from engs, but this array only has one value, which is the entire array from Engs
}
}

One way to inject server side information into the JavaScript portion of your application is "stringifying" the .Net object and calling JSON.Parse on the client side.
If you have the Json.NET nuget package from Newtonsoft you can use the static method JsonConvert.SerializeObject()
to turn almost any C# data structure into a JSON string.
After you place that string of JSON into your view using the templating feature of the Razor view engine, you can store it to a variable like so:
var engineerString = #JsonConvert.SerializeObject(Model.EngineerSchedule);
var dictionary = JSON.parse(engineerString);

As far as I can tell you are actually giving your javascript function strings as arguments since they are wrapped in quotes. Maybe there lies the confusion?

Related

How to pass a Json array to JPQL Where clause for IN operator?

I've a multiple drop down select box available to select the list of genres. I'm creating a JSON array in JavaScript with all the genres selected by user & passing them to the back end Java function for plotting graph.
Database : MySQL
JavaScript:
var items = {};
$(function() {
$('#genres1').change(function() {
console.log($(this).val());
items.genres = $(this).val();
}).multipleSelect({
width: '56%'
});
});
var genres = items.genres.map(function(e){
return JSON.stringify(e);
});
var selectedGenres = genres.join(", ");
alert(selectedGenres); // Outputs : "Action", "Horror" and so on.... based on selection
Java:
public static void myFun(String genre){
Logger.info("Genre"+genre); //prints "Action","Horror"
List<String> selectedGenres = Arrays.asList(genre);
//List<String> selectedGenres = Arrays.asList("Action","Horror"); //Correct output
Logger.info("Genre"+selectedGenres); //prints ["Action","Horror"]
String queryString="SELECT wD FROM sed WHERE genre IN (:genres)";
Query query1=JPA.em().createNativeQuery(queryString).setParameter("genres", selectedGenres);
}
I'm not knowing how the array has to be passed to the query.
//List<String> selectedGenres = Arrays.asList("Action","Horror"); //Correct output
This hardcoded value gives me the correct output. When I pass the "selectedGenres" array containing exactly the same as above input - "Action","Horror"I don't get the preferred output. I also tried to send "genre" as it is as a parameter but it did not work though. I'm getting empty response. Can someone correct me where I'm going wrong?
List<String> selectedGenres = Arrays.asList(genre);
Some API clarification: Arrays#asList accepts String... vargs, where every argument is an element value to create the actual List.
Back to your method: your input argument is String genre (a String) while #asList method is not aware that this genre string is actually an array (and should not), and it does its job correctly - upon receiving a single element (a String in our case), a single-dimensional List is created.
To solve the issue, you may want to try one of those options:
(if your string is JSON array) Use JSON parsing library (such as Jackson)
Try to split the input (genre) by a comma, and transform that array back to List.

Add items to JSON objects

I have a situation that I just cannot figure out how to do. I'm trying to add items to a JSON object that was sent from the controller.
Here's my models:
public class Model1
{
public Model2 item {get;set;}
public List<Model2> items {get;set;}
//
And in the page
var jsonData = #Html.Raw(JSON.Encode(Model))
This gives me the basic but empty model. Now in the page I fill in various fields and want to add the items into the model for posting. So:
jsonData.item.field1 = $("#field1").val();
Then I want to add to the list of items, but I cannot find anything that works:
jsonData.items.add(jsonData.item)
doesn't work throws an error.
jsonData.items.push(jsonData.item);
works but every item I add ends up the same. Meaning that when I add the second item there are two in the list but they have the same values. Any help would be appreciated.
As we know, Javascript can be used as OO language and classes and objects can be created on the fly in javascript.
Per my understanding, you are using below code to get class attributes in the JavaScript
var jsonData = #Html.Raw(JSON.Encode(Model))
When this JSON is returned to the client side, it is considered as single object.
So, you can declare a function, acting as class:
function Model2(jsonData ) {
this.name = jsonData.name;
this.discovered = jsonData.discovered;
};
var objModel2_1= new Model2(jsonData);
Now,
you can declare an array to add the objModel2.
var arrModel2=[];
// add new objects
attModel.push(objModel2_1);
Finally,
when you are done, you can use existing jsonData object to fill
i.e.
jsonData.item=objModel2_1;
jsonData.items=attModel;
Hope, this will help you.

How can I output the values in an array to a View in MVC with Razor?

Task
Output the values from an IEnumerable of simple types in a view.
Conditions
I have a model, passed in by the controller, that contains an array of simple values (in this case int). I want to output it into a variable in a JavaScript block in the view.
Standards
Without using a large foreach block and iterating over each item and then figuring out the commas, output the values in such a way that is similar to the statement seen below.
Example
var packageSummaryViewModel = new PackageSummaryViewModel([1,2,3,4,5,6,7]);
Currently this is what is happening:
View.cshtml
var packageSummaryViewModel = new PackageSummaryViewModel(#sensorIds);
Output
var packageSummaryViewModel = new PackageSummaryViewModel(System.Int32[]);
The way I do this is to use a JSON serializer, like JSON.NET. JSON stands for JavaScript Object Notation, so it's natural to use a JSON serializer to convert C#/.NET objects to Javascript objects.
#using Newtonsoft.Json
#model MyNamespace.MyObject
var myProperty = #Html.Raw(JsonConvert.SerializeObject(Model.MyProperty));
If Model.MyProperty is a List<int> containing the integers 1, 2, 3, Razor will render this as follows:
var myProperty = [1,2,3];
If Model.MyProperty is an instance of the following class
class C
{
public string X { get; set; }
public double Y { get; set; }
}
with X set to apple and Y set to 0.5, Razor will render this as follows:
var myProperty = {"X":"apple","Y":0.5};
The point is that this same approach works for any JSON-serializable C#/.NET object you might be passing as your model (or part of your model).

Is it possible to return two arrays at the view using one controller function at ASP.NET MVC4?

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?
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

create json string on client side

I am trying to create the JSON string / object that is equivalent to the following data on the server side. can somebody help?
Public Shared Function GetData() As List(Of Employee)
Dim list As New List(Of Employee)()
Dim newEmployee As New Employee()
newEmployee.EmployeeID = "1"
newEmployee.FirstName = "Sridhar"
newEmployee.Title = "Programmer"
newEmployee.BirthDate = "8/10/1979"
newEmployee.TitleOfCourtesy = "Programmer"
list.Add(newEmployee)
Return list
End Function
Employee is a class with the properties EmployeeId, FirstName, Title, Birthdate, TitleOfCourtesy.
Thanks,
sridhar.
Keep in mind that in Javascript there is no concept of a class, only objects. This also carries over into JSON. Look at this:
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
}
}
If you look at the first line, the "Employee" symbol does absolutely nothing for the JSON. Remember that we're dealing with ONLY objects.
Thats why this works, like you said.
[
{"EmployeeID":1,
"LastName":"Duggireddy",
"FirstName":"Sridhar",
"Title":"Programmer",
"TitleOfCourtesy":"Programmer",
"BirthDate":new Date(303091200000)}
]
To make this programatically, declare your employee objects, and just add them into an array, like so:
var employees = [];
employees.push(employee1); // you would use a loop, of course
employees.push(employee2);
...
var jsonString = parser.toJSON(employees); // or whatever you use.
That should give you a list of objects. Always ignore the class in JSON... .NET during the deserialization will attempt to coerce the object into that particular class. You only have problems if this fails - maybe because a variable is missing or of the wrong type.
Why not just use JSON.NET and let it handle encoding/decoding for you?
It will look like
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
}
}
Reference
I believe multiple instances of Employee in the JSON would look like this:
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
},
{
"EmployeeID":"2",
"FirstName":"Joe",
etc...
}
}
Maybe that is what you need?
There's a good jQuery plugin for JSON. It lets you go from a JavaScript object to JSON very easily.
http://code.google.com/p/jquery-json/

Categories