将 C# 对象列表转换为 JavaScript 对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18966367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:44:09  来源:igfitidea点击:

Convert C# List of object to JavaScript array of objects

c#jqueryasp.net-mvcjquery-ui

提问by Jeff

I am using jQueryUI's autocompleteto allow the search of users. The documentation states that I am able to use an array for the source of the data in the following format: [ { label: "Choice1", value: "value1" }, ... ]

我正在使用 jQueryUI 的自动完成功能来允许搜索用户。文档指出,我可以使用以下格式的数组作为数据源:[ { label: "Choice1", value: "value1" }, ... ]

I have a base class that provides a list of unique Userswhich is inherited by my view-model. The view model has the following function:

我有一个基类,它提供了一个Users由我的视图模型继承的唯一列表。视图模型具有以下功能:

public List<TestJson> GetUsers()
{
    return AvailableUsers
        .Select(u => new TestJson
            {
                Label = u.LastName + ", " + u.FirstName + "(" + u.UserId + ")",
                Value = u.UserId
            }).ToList();
}

public class TestJson
{
    public string Label { set; get; }
    public string Value { get; set; }
}

In my view, I use the above like so:

在我看来,我像这样使用上面的:

var userNameList = @Html.Raw(Json.Encode(Model.GetUsers()));

$("#UserName").autocomplete({
    source:userNameList 
});

Turns out userNameListis showing up like this:

原来userNameList是这样显示的:

[ { "Label": "Choice1", "Value": "value1" }, ... ]

instead of:

代替:

[ { label: "Choice1", value: "value1" }, ... ]

How can I get my array to show in the correct format?

如何让我的数组以正确的格式显示?

EDIT:Based on input from comments, I have verified that both those formats are indeed functionally equivalent. I did a little more testing and it turns out that labeland valueare case sensitive. Changing my members to lower case seems to do the trick, but I don't feel that solution is the best. Any suggestions on how to change the string on the left side of the : (what is this called?) to lowercase?

编辑:根据评论的输入,我已经验证这两种格式在功能上确实是等效的。我做了一个小测试多和事实证明,label并且value区分大小写。将我的成员更改为小写似乎可以解决问题,但我不认为该解决方案是最好的。关于如何将 :(这叫什么?)左侧的字符串更改为小写的任何建议?

采纳答案by Jeff

Comments by Jason P and Rob G are correct. The two formats in questions are equivalent. Turns out my issue was with the casing. DOH!

Jason P 和 Rob G 的评论是正确的。问题中的两种格式是等效的。原来我的问题是外壳。哦!

I just changed the properties in my class to be lower case. Thought, I would love to see an alternate solution. I will choose this one until a better one is submitted.

我只是将班级中的属性更改为小写。想,我很想看到一个替代解决方案。我会选择这个,直到提交更好的。

回答by Soner Sevinc

A simple Employee object:

一个简单的 Employee 对象:

public class Employee
{
public string Name { get; set; }
public string Age { get; set; }
public string ID { get; set; }   
}

Adding some instances of them to a List:

将它们的一些实例添加到列表中:

Employee oEmployee1 = 
new Employee{Name="Pini",ID="111", Age="30"};

Employee oEmployee2 = 
new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" };
Employee oEmployee3 = 
new Employee { Name = "Yoni", ID = "Biton", Age = "20" };

List<Employee> oList = new List<Employee>() 
{ oEmployee1, oEmployee2, oEmployee3 };

Serializing then:

然后序列化:

System.Web.Script.Serialization.JavaScriptSerializer oSerializer = 
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);

And here is the output:

这是输出:

[{"Name":"Pini","Age":"30","ID":"111"},
{"Name":"Yaniv","Age":"31","ID":"Cohen"},
{"Name":"Yoni","Age":"20","ID":"Biton"}]

Also below link has similar example

下面的链接也有类似的例子

Convert Object to JSON in MVC 4

在 MVC 4 中将对象转换为 JSON

回答by Colin Young

I assume you are using MVC. WebAPI will default to camelCase while MVC defaults to PascalCase.

我假设您正在使用 MVC。WebAPI 将默认为驼峰式,而 MVC 默认为 PascalCase。

See also: Proper JSON serialization in MVC 4and http://www.matskarlsson.se/blog/serialize-net-objects-as-camelcase-json.

另请参阅:MVC 4 中的正确 JSON 序列化http://www.matskarlsson.se/blog/serialize-net-objects-as-camelcase-json

回答by Ahmed Elbendary

        //View.cshtml
<script type="text/javascript">
    var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.GetUsers()))');
</script>

回答by satya prakash

If you passing List of object though MVC model and want to store it an array variable in script section on .cshtml page PFB code snipt :-

如果您通过 MVC 模型传递对象列表并希望将其存储在 .cshtml 页面 PFB 代码片段的脚本部分中的数组变量:-

@Html.Raw(Json.Encode(Model.ListPropertyName))