asp.net mvc json result format
        Posted  
        
            by ile
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by ile
        
        
        
        Published on 2010-03-29T19:04:44Z
        Indexed on 
            2010/03/29
            19:13 UTC
        
        
        Read the original article
        Hit count: 568
        
public class JsonCategoriesDisplay
    {
        public JsonCategoriesDisplay() { }
        public int CategoryID { set; get; }
        public string CategoryTitle { set; get; }
    }
    public class ArticleCategoryRepository
    {
        private DB db = new DB();  
        public IQueryable<JsonCategoriesDisplay> JsonFindAllCategories()
        {
            var result = from c in db.ArticleCategories                         
                         select new JsonCategoriesDisplay
                         {
                             CategoryID = c.CategoryID,
                             CategoryTitle = c.Title                            
                         };
            return result;
        }
          ....
    }
public class ArticleController : Controller
    {
        ArticleRepository articleRepository = new ArticleRepository();
        ArticleCategoryRepository articleCategoryRepository = new ArticleCategoryRepository();
        public string Categories()
        {
            var jsonCats = articleCategoryRepository.JsonFindAllCategories().ToList();
            //return Json(jsonCats, JsonRequestBehavior.AllowGet);
            return new JavaScriptSerializer().Serialize(new { jsonCats});
        }
    }
This results with following:
{"jsonCats":[{"CategoryID":2,"CategoryTitle":"Politika"},{"CategoryID":3,"CategoryTitle":"Informatika"},{"CategoryID":4,"CategoryTitle":"Nova kategorija"},{"CategoryID":5,"CategoryTitle":"Testna kategorija"}]}
If I use line that is commented and place JsonResult instead of returning string, I get following result:[{"CategoryID":2,"CategoryTitle":"Politika"},{"CategoryID":3,"CategoryTitle":"Informatika"},{"CategoryID":4,"CategoryTitle":"Nova kategorija"},{"CategoryID":5,"CategoryTitle":"Testna kategorija"}]
But, I need result to be formatted like this:
{'2':'Politika','3':'Informatika','4':'Nova kateorija','5':'Testna kategorija'}
Is there a simple way to accomplish this or I will need to hardcode result?
Thanks in advance!
© Stack Overflow or respective owner