ViewBag on a Javascript code mvc 4 - c#

I am having a trouble doing this: I have a ViewBag that contains the list of documents Id's and the response time for each one, created like this:
Controller:
ViewBag.Documents= (from n in db.DocumentType
select new {a = n.DocumentTypeId, b=n.ResponseTime});
Based on the document that the user selected on a dropdownlist, the javascript code calculates the real duration of processing the document (duration).
DocumentId(int) Response(int)
1 2 days
2 3 days
3 1 day
The complete javascript code calculates the final date based on response time without weekends and holidays, but the only part that it is not working is the following part of JavaScript code:
JavaScript at the view:
function CalculateTime(documenttype) {
var duration= 0;
var jScriptArray= new Array();
var array = '#Html.Raw(Json.Encode(ViewBag.Documents))';
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < 2; j++) {
jScriptArray [i][j] = array [i][j];
}
}
for (i = 0; i < jScriptArray.length; i++) {
if (documenttype== jScriptArray [i][0]) duration= jScriptArray [i][1];
}
return duration;
}
I already have the correct documenttype variable based on a dropdownlist but this script is not working. I think is the way I want to use the ViewBag, but I am not pretty sure. What I need to know is: what is wrong with my code or another way to do this.
Thanks in advance

Just remove quotes
var array = #Html.Raw(Json.Encode(ViewBag.Documents));

Just remove the quotes(') and you have to Newtonsoft.Json for this.
var array = #Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.Documents);
This will work.

A friend of mine helped me solve my problem. Some of you told me to use Json, so we did this:
Controller:
using System.Web.Script.Serialization;
using Newtonsoft.Json;
...
var timeList= db.DocumentType.ToList();
ViewBag.ResponseTimes= new JavaScriptSerializer().Serialize(
JsonConvert.SerializeObject(new
{
times= (from obj in timeList
select new { DocumentTypeId= obj.DocumentTypeId, ResponseTime= obj.ResponseTime})
}, Formatting.None));
JavaScritp at the View:
function CalculateTime(documenttype) {
var duration = 0;
var jScriptArray = new Array();
var array = $.parseJSON(#Html.Raw(ViewBag.ResponseTimes));
for (i = 0; i < array.times.length; i++) {
if (parseInt(documenttype) == array.times[i].DocumentTypeId) {
duration= array.times[i].ResponseTimes;
}
}
return duration;
}
Thanks!
PS: I don't know which of both answers give the acceptance cause we used part of both....

Related

C# Instantiate List by Calling a Function

Is there a more minimal way to write the following:
var voucherCodes = new List<string>();
for (int i = 0; i < 10; i++)
{
voucherCodes.Add(GenerateCode(VoucherCodeLength));
}
I would like to do something like this:
// ten items would be added to the list so long as GenerateCode returns a string
var voucherCodes = new List<string>(GenerateCode(VoucherCodeLength), 10);
Granted, I could create my own function, but I was wondering if there was something that already exists.
I can't say if it's better, but you can use the folloing LINQ "one-liner":
var voucherCodes = Enumerable.Range(0, 10).Select(_ => GenerateCode(VoucherCodeLength)).ToList();
or specifically for this call, and if the VoucherCodeLength is constant (or does not change and has no side effects), an even shorter:
var voucherCodes = Enumerable.Repeat(VoucherCodeLength, 10).Select(GenerateCode).ToList();
Another linqy way
var voucherCodes = Enumerable.Repeat(GenerateCode(VoucherCodeLength), 10).ToList();

pass a list of my model to Transaction in ArangoDB-NET

I simply worked with Transaction in ArnagoDB_NET when I work with one item of my model. but I have a problem when I want to pass a list of my model.
var transactionResult= Context.Transaction.WriteCollection("User").Execute<Dictionary<string, object>>(
string.Format(#"
function () {{
var db = require('internal');
if(!db.User.exists('{0}'))
db.User.save( {{ _key:'{0}', UserAppState:1 }});
}}
// and other actions
return {{ 'Executed': true }};
}}", myModel.userId))
above example fine worked, but when I want to pass a list of my model, how can I iterate them into string(or ArangoDB script)?
for example:
string.Format(#"
function () {{
var db = require('internal');
for (i = 0; i < {0}.count; i++){{ // I know didn't work this block code!
if(!db.User.exists('{i.key}'))
db.User.save( {{ _key: ""'i.key'"", UserAppState:1 }});
// and other actions
}}
return {{ 'Executed': true }};
}}", lstMyModels);
can any one help me?!
I don't think this would be possible given your example, since you are combining C# string interpolated object with ArangoDB transaction functionality which doesn't work together just by combining them into single query.
Your first example works because it's using primitive value which you pass into the string, however in the second example you want to pass list of objects and iterate through them using cycle that is not in any way connected to the list itself. This line
for (i = 0; i < {0}.count; i++) {
won't work because lstMyModels is a C# list object and you would actually end up with a string interpolated like this:
for (i = 0; i < System.Collections.Generic.List`1[System.Object].count; i++) {
which makes no sense to the ArangoDB which needs to execute the transaction. Moreover the i variable is a simple number serving as current cycle iteration index therefore calling i.key is also wrong.
Instead of complicated string interpolation you should try to use transaction parameter passing which is supported by the ArangoDB-NET driver.
EDIT:
Let's say you have object like this:
public class TransactionEntity
{
public string Foo { get; set; }
}
Then you can pass it as transaction parameter for example like this:
var transactionData = new List<TransactionEntity>
{
new TransactionEntity
{
Foo = "string1"
},
new TransactionEntity
{
Foo = "string2"
},
new TransactionEntity
{
Foo = "string3"
}
};
var transactionResult = db.Transaction
.WriteCollection("myCollection")
.Param("data", transactionData)
.Execute<List<TransactionEntity>>(#"
function (params) {
var db = require('internal').db;
for (var i = 0; i < params.data.length; i++) {
db.myCollection.save(params.data[i]);
}
return db._query('FOR doc IN myCollection SORT TO_NUMBER(doc._key) RETURN doc').toArray();
}
");

Table of strings in C#

Is there a way of creating a table with each cell containing a string in C# ?
The closest thing I found is multidimensional arrays string[,] names;, but it seems like its length needs to be defined which is a problem to me.
Here is what my code looks like :
string[] namePost;
int[] numbPage;
string post="";
string newPost;
int i=0;
int j=0;
foreach (var line in File.ReadLines(path).Where(line => regex1.Match(line).Success))
{
newPost = regex1.Match(line).Groups[1].Value;
if (String.Compare(newPost, post) == 0)
{
j = j + 1;
}
else
{
namePost[i] = post;
numbPage[i] = j;
post = newPost;
j = 1;
i = i + 1;
}
}
Each instance of the for writes the name of the new "post" in a cell of namePost. In the end, the namePost table stores the name of all the posts that are different from one another.
What is the best way to achieve that ?
If you are simply trying to store the posts, you can use the List class from the System.Collections.Generic namespace:
using System.Collections.Generic;
List<String> namePost = new List<String>();
Then, instead of namePost[i] = post;, use
namePost.Add(post);
DataTable
https://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspx
Use this, no need to define length at all.
Useful guide and examples:
http://www.dotnetperls.com/datatable
You can just use a
var table = new List<List<string>>();
This would give you a dynamic 2D table of strings.
This will give you all your unique posts. If you want the result as a list you can just do a
.ToList ()
with the result.
static IEnumerable<string> AllPosts(Regex regex, string filePath)
{
return File.ReadLines (filePath)
.Where (line => regex.Match (line).Success)
.Select (line => regex.Match (line).Groups [1].Value)
.Distinct ();
}

Access C# List inside Javascript

On the server side I create a list
List<object> data = new List<object>();
for (var j = 0; j < items.Count(); j++)
{
var temp = groups.Where(customfilter);
data.Add(Html.Raw(Json.Encode(temp)));
}
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
var serializedData = serializer.Serialize(data);
Inside Javascript the folowing won't work for anything but primitive types.
var localData = #data;
This is the error:
System.Collections.Generic.List`1[System.Object]
What am I missing?
I am assuming that the C# code you posted is a Controller action method.
You would need to have your controller method return a JsonResult, and then use a JSON library to deserialize it.
Something like
public class MyController: Controller
{
public JsonResult MyAction ()
{
var data = new List<object>();
for (var j = 0; j < items.Count(); j++)
{
var temp = groups.Where(customfilter);
data.Add(temp);
}
return Json (data, JsonRequestBehavior.AllowGet);
}
}
Note how you don't need to serialize every item as you add it to the list.
From the client side, you can call your method and deserialize the result to a list. You can do it like this:
$.ajax ({ url:'/My/MyAction'}).done (function (data) {
var myList = JSON.parse (data);
});
Edit:
After some testing, I found that you can access the data by doing:
var myList = data;
Not sure why, but "data" is sent directly as an array.
Hope it helps!
First of all check this link http://james.newtonking.com/pages/json-net.aspx
Second
var temp = groups.Where(customfilter).ToList();
If you use where cast it to list or it will be something like Query object *(I dont remember exactly type)
Or if you want to select one object try groups.FirstOrDefault
Third
data.Add(temp);
Serializer will do his job to convert it.

The best way to pass rows of an SQL Database to Javascript?

So, recently I've been looking into the HTML5 Indexeddb feature which is controlled with Javascript, and how to incorporate this with an SQL Server database to share and copy information across so that a version of the database is available offline.
The conundrum that I have is finding the best way to pass a set of objects from an SQL Server database through to the javascript of a browser, using C# to get the values from the database.
Though there are many little "hacks" that can be done (e.g Putting data into labels and then having the Javascript just pick it up document.getElementById("DataHere").value;) I was wondering if there were more efficient ways of passing the contents of a database across?
At the moment I have a method that generates an array of strings (all in the JSON format, using the JSON.Net package) as an example of what would be returned from the database.
public string[] GenerateEmployeeSample() {
List<Employee> listEmps = new List<Employee>();
string[] listJSON = new string[64];
string[] FirstNames = {"Alonso", "Alfred", "Angus", "Alfresco" };
string[] LastNames = {"Johnson","Williams", "Zelwegger", "Jones" };
string[] Departments = {"Finance", "Cleaning", "Pusher", "Stairs" };
string emailEnd = "#email.com";
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
Employee tempEmp = new Employee();
tempEmp.FirstName = FirstNames[i];
tempEmp.LastName = LastNames[j];
tempEmp.Department = Departments[k];
tempEmp.Email = FirstNames[i] + "." + LastNames[j] + emailEnd;
listEmps.Add(tempEmp);
}
}
}
int count = 0;
foreach(Employee emp in listEmps){
string tempString = JsonConvert.SerializeObject(emp);
listJSON[count] = tempString;
count++;
}
return listJSON;
}
So now I have a set of data, how would I be able to pass this array through to Javascript?
I apologise if this is a trivial question but Javascript is still rather new to me, and after reading through quite a few examples that either didn't do what I wanted or just outright didn't work I am at a bit of a loss.
Thanks very much for reading!
To be more specific, you would make a resource (be it an aspx page or or a json file etc) that returns a JSON string when requested. You're already partway there with this step, because you've already got the code for serializing objects as JSON. A simple way of doing this would be to have a page that outputs the return value of this function using Response.Write(GenerateEmployeeSample());
Then you would use the XMLHttpRequest object to request this resource, and parse the returned JSON using javascript's JSON.parse, which returns a native javascript object. You may then do with this object as you please.

Categories