【问题标题】:webmethod return values form base classwebmethod 从基类返回值
【发布时间】:2013-06-18 09:29:36
【问题描述】:
{"__type":"CountryModel","dt":null,"ds":null,"dtRow":null,"strSQL":{"Capacity":16,"MaxCapacity":2147483647,"Length":0},"iCnt":0,"ConnType":"FP","Code":"AE","Value":"United Arab Emirates"},{"__type":"CountryModel","dt":null,"ds":null,"dtRow":null,"strSQL":{"Capacity":16,"MaxCapacity":2147483647,"Length":0},"iCnt":0,"ConnType":"FP","Code":"AF","Value":"Afghanistan"},{"__type":"CountryModel","dt":null,"ds":null,"dtRow":null,"strSQL":{"Capacity":16,"MaxCapacity":2147483647,"Length":0},"iCnt":0,"ConnType":"FP","Code":"AG","Value":"Antigua and Barbuda"},

这是我通过json返回的webmethod,但问题是,asp.net从我继承的基类返回值,如何解决这个问题?虽然可以工作,但是数据被浪费了,因为我不想返回值,知道吗?

BaseModel.cs

   public string ConnType="";
   public datatable dt;

CountryModel.cs:

public class CountryModel:BaseModel{
   public List<MenuFunctionModel> AssignList()
{
    var _List = new List<MenuFunctionModel>();

    foreach (DataRow dr in dt.Rows)
    {
        _List.Add(new MenuFunctionModel
        {
            Code = dr["Code"].ToString(),
            Title = dr["Title"].ToString(),
            Description = dr["Description"].ToString(),
            Location = dr["Location"].ToString() + dr["FileName"].ToString()
        });
    }
    return _List;
}
}

网络服务 API:

    [WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<CountryModel> loadCt()
{
    CountryModel _Country = new CountryModel();
    _Country.SelectAll();
    return _Country.AssignList();
}

【问题讨论】:

  • 是否只返回MenuFunctionModel的部分数据?
  • 是的,我只是想返回列表中的部分,但由于 List,它看起来返回了所有内容?
  • 这是由于您在 webmethod 中使用的返回类型 (List&lt;CountryModel&gt;)。你可以使用另一个只包含所需字段数的类,或者使用任意类型
  • 我可以参考任何示例链接吗?或者我将每个基类公共变量更改为私有,但这将对其他类产生更大的变化影响,因为我计划将所有变量用作全局变量
  • 应该是继承到导致问题的基本模型的类,有什么解决办法吗?

标签: asp.net json web-services


【解决方案1】:

你可以从你的 WebMethod 中返回任意类型:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Object loadCt()
{
    CountryModel _Country = new CountryModel();
    _Country.SelectAll();
    return _Country.AssignList().Select(m=> new{ Code=m.Code, Title =m.Title}); //select those fields only which you want to return
}

更多参考,Click here

【讨论】:

  • 永远欢迎!我们都非常感谢这个伟大的社区社区!
猜你喜欢
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多