开发者

How do I pass my data to a JsonResult so that it formats correctly

开发者 https://www.devze.com 2023-04-12 16:42 出处:网络
I am using a MooTools TextboxList in my MVC app to create an autocomplete Tag suggester, similar to the StackOverflow one.

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."


It's an array of arrays of objects. You could generate it like this:

return Json(new[] { new object[] { 32, "Science", null, null } });

and within your select action you could try something along the lines of:

public ActionResult Suggest(string search)
{
    var tags = from t in db.Tags
               where t.Text.Contains(search)
               select new object[] { t.TagID, t.Text };

    return Json(tags.ToList(), JsonRequestBehavior.AllowGet);
}


Based on another question, I ended up going old-school on it... building the string manually.

    public ContentResult Suggest(string search)
    {
        var tags = from t in db.Tags
                   where t.Text.Contains(search)
                   orderby (t.Text)
                   select t;

        var builder = new StringBuilder();
        builder.Append("[");
        foreach (Tag tag in tags)
            builder.AppendFormat("[{0}, \"{1}\", null, null]", tag.TagID, tag.Text);
        var result = builder.ToString().TrimEnd(new char[] { ',', ' ' }) + "]";

        ContentResult res = new ContentResult();
        res.Content = result;

        return res;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消