Return 列出 obj/variables 而不是模型中的全部
Return listed obj/variables rather than all in model
如何配置我的代码,以便在我的控制器的 jsonresult 方法中只有 featureid 和 featurename 变量 return,而不是我模型中的所有对象 returning.
业务逻辑:
public static List<FeatureModel> LoadFeatures(){
string sql = @"SELECT FeatureId, FeatureName
FROM Feature";
return SqlDataAccess.LoadData<FeatureModel>(sql);}
型号:
public class FeatureModel{
public int FeatureId { get; set; }
public string FeatureName { get; set; }
public string FeatureDescription { get; set; }}
控制器:
public JsonResult ViewFeatures(){
var data = LoadFeatures();
List<FeatureModel> feat = new List<FeatureModel>();
foreach (var row in data)
{
feat.Add(new FeatureModel
{
FeatureId = row.FeatureId,
FeatureName = row.FeatureName,
});
}
return Json(feat, JsonRequestBehavior.AllowGet);
}
JS/Ajax得到结果:
[{"FeatureId":0,"FeatureName":"Insights","FeatureDescription":null}]
一种简单的方法是使用 System.Linq
public JsonResult ViewFeatures(){
var data = LoadFeatures();
List<FeatureModel> feat = new List<FeatureModel>();
foreach (var row in data)
{
feat.Add(new FeatureModel
{
ModuleId = row.ModuleId,
FeatureName = row.FeatureName,
});
}
return Json(feat.Select(x => new {x.FeatureId, x.FeatureName }), JsonRequestBehavior.AllowGet);
如何配置我的代码,以便在我的控制器的 jsonresult 方法中只有 featureid 和 featurename 变量 return,而不是我模型中的所有对象 returning.
业务逻辑:
public static List<FeatureModel> LoadFeatures(){
string sql = @"SELECT FeatureId, FeatureName
FROM Feature";
return SqlDataAccess.LoadData<FeatureModel>(sql);}
型号:
public class FeatureModel{
public int FeatureId { get; set; }
public string FeatureName { get; set; }
public string FeatureDescription { get; set; }}
控制器:
public JsonResult ViewFeatures(){
var data = LoadFeatures();
List<FeatureModel> feat = new List<FeatureModel>();
foreach (var row in data)
{
feat.Add(new FeatureModel
{
FeatureId = row.FeatureId,
FeatureName = row.FeatureName,
});
}
return Json(feat, JsonRequestBehavior.AllowGet);
}
JS/Ajax得到结果:
[{"FeatureId":0,"FeatureName":"Insights","FeatureDescription":null}]
一种简单的方法是使用 System.Linq
public JsonResult ViewFeatures(){
var data = LoadFeatures();
List<FeatureModel> feat = new List<FeatureModel>();
foreach (var row in data)
{
feat.Add(new FeatureModel
{
ModuleId = row.ModuleId,
FeatureName = row.FeatureName,
});
}
return Json(feat.Select(x => new {x.FeatureId, x.FeatureName }), JsonRequestBehavior.AllowGet);