如何将数据传递给 JsonResult 以便其格式正确
我在 MVC 应用程序中使用 MooTools TextboxList 来创建自动完成标签建议器,类似于堆栈溢出一。
该脚本使用 Json 来执行建议。它似乎期望的 Json 字符串与我能够生成的不同。从脚本的演示来看,它应该看起来像这样:
[[32,"Science",null,null]]
但我不知道如何让字符串像这样从 MVC 中出来。我得到的最好的看起来更像是:
[{"id":11,"text":"Science"}]
显示实际的字段名称。
这是我的控制器方法:
public JsonResult Suggest(string search)
{
JsonResult jsonresult = new JsonResult();
var tags = from t in db.Tags
where t.Text.Contains(search)
select new {id=t.TagID, text=t.Text};
var result = DoSomethingTo(tags); // <---????????
jsonresult.Data = result;
jsonresult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsonresult;
}
我尝试了将变量传递到 JsonResult.Data 的几种变体,但运气不佳。我尝试过数组、自定义对象等,但我只是不明白。我确信这非常
编辑:应该说“我确信这非常容易”。
I am using a MooTools TextboxList in my MVC app to create an autocomplete Tag suggester, similar to the StackOverflow one.
The script uses Json to do the suggestions. The Json string it seems to expect is different than I am able to generate. From the script's demo, it should look something like this:
[[32,"Science",null,null]]
But I can't figure out how to get the string to come out of MVC quite like that. Best I get looks more like:
[{"id":11,"text":"Science"}]
With the actual field names showing up.
Here is my controller method:
public JsonResult Suggest(string search)
{
JsonResult jsonresult = new JsonResult();
var tags = from t in db.Tags
where t.Text.Contains(search)
select new {id=t.TagID, text=t.Text};
var result = DoSomethingTo(tags); // <---????????
jsonresult.Data = result;
jsonresult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsonresult;
}
I've tried several variations of passing variables into the JsonResult.Data without much luck. I've tried arrays, custom objects, etc. I'm just not getting it. I'm certain it's very
Edit: That should have said "I'm certain it's very easy."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它是一个对象数组的数组。您可以像这样生成它:
并且在您的选择操作中您可以尝试以下内容:
It's an array of arrays of objects. You could generate it like this:
and within your select action you could try something along the lines of:
基于 另一个问题,我最终采用了老派的方式......手动构建字符串。
Based on another question, I ended up going old-school on it... building the string manually.