什么是从C#返回数组的JavaScript最好的(简单明了)的方式 [英] What is the best(easy and clear) way to return arrays from C# to javascript

查看:89
本文介绍了什么是从C#返回数组的JavaScript最好的(简单明了)的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这里有很多类似的问题,但我没有找到任何被要求完全一样的东西。

我正在开发使用ASP.NET和MVC4的项目。我使用的aspx作为视图引擎。我有我的观点一个javascript code,它得到的输入值的表,并创建基于它们的图形。

我用下面

查询获取这些值从我的数据库

  VAR的查询=从B在db.SchoolTestsPerModulePerStudent
                    其中,b.StudentID.Equals(2)
                    选择B:

现在,我的问题是,如果我有这些成果在阵列(我没有想通了呢,怎么给B,拆分其结果两个数组,一个包含测试的id和其他含学生的年级然而,但我希望我会很快),什么是从C#这些阵列返回的javascript最好的(简单明了)的方式?


解决方案

连载的对象的 JSON 。如果你的模型,例如,的IEnumerable<串GT;

控制器

 公众的ActionResult指数()
{
    IList的<串GT;串=新的List<串GT;();
    strings.Add(蟒);
    strings.Add(C#);
    strings.Add(使用Javascript);
    strings.Add(红宝石);
    返回查看(串);
}

查看

  @ Json.En code(型号)

结果:

  [蟒,C#,使用Javascript,红宝石]

提取阵列


  

如何给B,拆分其结果两个数组


使用LINQ。

  VAR学生= db.SchoolTestsPerModulePerStudent.Where(X => x.StudentId == 2);
VAR日期= student.Select(X => x.TestDate);
VAR等级= student.Select(X => x.TestGrade);

I know that there are a lot similar questions here, but I did not find anyone which is asking exactly the same thing.

I am developing a project using ASP.NET and MVC4. I am using aspx as a view engine. I have a javascript code at my views, which gets as input a table of values, and creates a graph based on them.

I get those values from my database using the query below

        var query = from b in db.SchoolTestsPerModulePerStudent
                    where b.StudentID.Equals(2)
                    select b;

Now, my question is if I have these results in arrays (I did not figured out yet, how given b, to split its results in two arrays, one containing the id of test and the other containing the grade of the student yet, but I hope I will soon), what is the best(easy and clear) way to return these arrays from C# to javascript?

解决方案

Serialise the object to JSON. If your Model is, for example, IEnumerable<string>:

Controller

public ActionResult Index()
{
    IList<string> strings = new List<string>();
    strings.Add("Python");
    strings.Add("C#");
    strings.Add("Javascript");
    strings.Add("Ruby");
    return View(strings);
}

View

@Json.Encode(Model)

Result:

["Python","C#","Javascript","Ruby"]

Extracting arrays

how given b, to split its results in two arrays

Use Linq.

var student = db.SchoolTestsPerModulePerStudent.Where(x => x.StudentId == 2);
var dates = student.Select(x => x.TestDate);
var grades = student.Select(x => x.TestGrade);

这篇关于什么是从C#返回数组的JavaScript最好的(简单明了)的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆