2015-01-02 110 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; 
    }