【问题标题】:Return listed obj/variables rather than all in model返回列出的 obj/变量,而不是模型中的全部
【发布时间】:2021-03-03 09:31:40
【问题描述】:

如何配置我的代码,以便只有 featureid 和 featurename 变量在我的控制器的 jsonresult 方法中返回,而不是我的模型中的所有对象都返回。

业务逻辑:

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}]

【问题讨论】:

    标签: c# .net visual-studio model-view-controller


    【解决方案1】:

    一种简单的方法是使用 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);
    

    【讨论】:

      猜你喜欢
      • 2016-04-03
      • 1970-01-01
      • 2011-12-27
      • 2013-05-30
      • 2012-01-01
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      • 2020-06-22
      相关资源
      最近更新 更多