我正在使用 jQueryUI 的 autocomplete允许搜索用户。文档指出我可以使用以下格式的数组作为数据源:[ { label: "Choice1", value: "value1"}, ... ]
我有一个基类,它提供了一个由我的 View 模型继承的唯一 Users
列表。 View 模型具有以下功能:
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; }
}
在我看来,我是这样使用上面的:
var userNameList = @Html.Raw(Json.Encode(Model.GetUsers()));
$("#UserName").autocomplete({
source:userNameList
});
原来 userNameList
是这样显示的:
[ { "Label": "Choice1", "Value": "value1" }, ... ]
代替:
[ { label: "Choice1", value: "value1" }, ... ]
如何让我的数组以正确的格式显示?
编辑:根据评论的输入,我已经验证这两种格式在功能上确实是等价的。我做了更多测试,结果发现 label
和 value
区分大小写。将我的成员更改为小写似乎可以解决问题,但我不认为该解决方案是最好的。关于如何将 :(这叫什么?)左侧的字符串更改为小写的任何建议?
最佳答案
//View.cshtml
<script type="text/javascript">
var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.GetUsers()))');
</script>
关于c# - 将 C# 对象列表转换为 JavaScript 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18966367/