2015-01-02 108 views
-3

我试图构造如下C#中的动态属性

CateogoryScores [ 
    "CatShoes" : 10, 
    "CatDress" : 20 
] 

的Catshoes和CatDress是在一个数据库中的实际值。我需要这个形状,因为我需要能够在JavaScript中编写以下内容。 CateogoryScores [“CatShoes”]等

这是我的模型

public class CategoryScoresDTO 
{ 
    public string CategoryId { get; set; } 
    public string TraqCategoryScore { get; set; } 
} 

这是我的函数,从表中获取数据

private IEnumerable<CategoryScoresDTO> GetCatgoryScoresByBrandId(string brandId) 
    { 

     var scores = from s in db.CategoryScoresModel 
        where s.BrandId == brandId 
        select new CategoryScoresDTO() 
        { 
         CategoryId = s.CategoryId, 
         TraqCategoryScore = s.TraqCategoryScore 
        }; 

     return scores; 
    } 

显然,这不是外形我想返回它只是一个列表不是我需要的正确形状

+2

术语“形状”是莫名其妙。你的意思是你想要将结果序列化为JSON格式吗? –

+0

你的形状是什么意思? – Mayank

+0

对不起是该对象将被序列化到JSON,它已经这样做了,它的更多关于具有得到的值,以成为该阵列的特性 –

回答

0

你应该可以在WebApi控制器中这样做。

private IHttpActionResult GetCatgoryScoresByBrandId(string brandId) 
    { 

     var scores = from s in db.CategoryScoresModel 
        where s.BrandId == brandId 
        select new CategoryScoresDTO() 
        { 
         CategoryId = s.CategoryId, 
         TraqCategoryScore = s.TraqCategoryScore 
        }; 

     return Json(scores); 
    } 
0

感谢您的意见,但最终我需要返回一个Dictionary对象得到期望的结果

private Dictionary<string, string> GetCatgoryScoresByBrandId(string brandId) 
    { 

     var scores = from s in db.CategoryScoresModel 
        where s.BrandId == brandId 
        select new CategoryScoresDTO() 
        { 
         CategoryId = s.CategoryId, 
         TraqCategoryScore = s.TraqCategoryScore, 

        }; 

     Dictionary<string, string> categoryScores = new Dictionary<string, string>(); 

     categoryScores = scores.ToDictionary(x => x.CategoryId, x => x.TraqCategoryScore); 


     return categoryScores; 
    }