我正在尝试构建以下
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;
}
显然这不是我想要返回的形状,因为它只是一个列表而不是我需要的正确形状
答案 0 :(得分:0)
你应该可以在Web Api控制器中使用这样的东西。
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);
}
答案 1 :(得分: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;
}