Return listed obj/variables rather than all in model

Viewed 37

How can I configure my code, so that only the featureid and featurename variables return in my controller's jsonresult method, rather than all the objects in my model returning.

Business Logic:

public static List<FeatureModel> LoadFeatures(){
string sql = @"SELECT FeatureId, FeatureName
                        FROM Feature";
return SqlDataAccess.LoadData<FeatureModel>(sql);}

Model:

public class FeatureModel{

public int FeatureId { get; set; }
public string FeatureName { get; set; }
public string FeatureDescription { get; set; }}

Controller:

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 get results:

[{"FeatureId":0,"FeatureName":"Insights","FeatureDescription":null}]
1 Answers

One easy way is to use 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);
Related