asp.net mvc json result format
- by ile
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!