You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET中控制器返回ViewModel至视图作为AJAX对象后如何访问字段值

访问AJAX返回的ViewModel数据

嘿,恭喜你已经成功把ViewModel数据通过AJAX拿到前端啦!从你给出的日志格式来看,返回的数据是交替出现的department和section对象集合(大概率是JavaScript数组),下面给你几种实用的访问方式:

1. 遍历整个数据集(最常用场景)

假设你的AJAX成功回调里拿到的响应数据存在变量response中,你可以用forEach循环逐个处理每个对象,通过属性区分类型:

// 示例AJAX请求
$.ajax({
  url: '/你的控制器接口地址',
  method: 'GET',
  success: function(response) {
    // 遍历每一项数据
    response.forEach(item => {
      // 判断当前对象是department还是section
      if (item.shortName) { // department有shortName属性
        console.log('部门ID:', item.id);
        console.log('部门名称:', item.name);
        console.log('部门简称:', item.shortName);
      } else if (item.laModiDate) { // section有laModiDate属性
        console.log('部门组ID:', item.id);
        console.log('部门组名称:', item.name);
        console.log('最后修改日期:', item.laModiDate);
      }
    });
  }
});

2. 直接访问指定位置的对象

如果你清楚某个对象在集合中的位置(比如第一个department是索引0,第一个section是索引1),可以直接通过下标访问:

success: function(response) {
  // 取第一个department
  const firstDepartment = response[0];
  console.log(firstDepartment.name); // 输出 "Development"
  
  // 取第一个section
  const firstSection = response[1];
  console.log(firstSection.laModiDate); // 输出 "2018-03-01"
}

3. 按类型分组整理数据

如果想把department和section分开存储,方便后续单独使用,可以在遍历的时候分类收集:

success: function(response) {
  const departments = [];
  const sections = [];
  
  response.forEach(item => {
    // 根据属性判断类型并分组
    'shortName' in item ? departments.push(item) : sections.push(item);
  });
  
  // 现在可以单独操作部门数组
  console.log('所有部门列表:', departments);
  // 或者单独操作部门组数组
  console.log('所有部门组列表:', sections);
}

小提醒

  • 你可以先在回调里执行console.log(response)和console.log(typeof response),确认返回数据的类型(是数组还是普通对象),这样能更精准地处理。
  • 如果返回的是嵌套对象而非数组,就用for...in循环遍历属性:
success: function(response) {
  for (const key in response) {
    const item = response[key];
    // 同样按照属性判断类型并访问数据
  }
}

内容的提问来源于stack exchange,提问作者nevil david

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:08:02