asp.net viewmodel返回视图为ajax对象;如何访问字段和值

时间:2018-03-03 11:16:31

标签: asp.net ajax asp.net-ajax

我从控制器返回一个viewmodel数据,成功地查看为ajax对象。我无法弄清楚如何访问数据。

视图中的Ajax代码是

<script>
function GetDepartmentsSections() {
    var myData = { CompanyName: $("#CompanyName").val() };

    $.ajax({
        headers:
                    {
                        "RequestVerificationToken": '@GetAntiXsrfRequestToken()'
                    },
        url: "/Shifts/Get_Department_Section",
        type: "POST",
        data: myData,
        success: function (data) {
            data.forEach(function (element) {
                console.log(element)

            });
        },
        error: function () {

        }
    });
}

$("#CompanyName").on('change', GetDepartmentsSections);

此处日志正确显示数据

department:Object {id:6,name:&#34; Development&#34;,shortName:&#34; DVT&#34;,...}

section:Object {id:7,name:&#34; section1&#34;,laModiDate:&#34; 2018-03-01&#34;,...}

department:Object {id:9,name:&#34; Finance&#34;,shortName:&#34; FIN&#34;,...}

section:Object {id:18,name:&#34; section3&#34;,laModiDate:&#34; 2018-03-01&#34;,...}

依旧......

现在如何访问部门和部门组的值?我是ajax和.net的新手。在过去的几个小时里一直坚持这一点。我期待着... ...

element.department.id  'or' element.section.name 'and so on...'

控制器如下

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Get_Department_Section(string CompanyName)// To select Departments/sections for 'assign shifts'
    {
        int CompID = await _context.Company.Where(i => i.Name == CompanyName).Select(i => i.ID).FirstOrDefaultAsync();

        var DepSec = _context.Department.Where(i => i.CompanyID == CompID).Join(_context.Section, d => d.ID, s => s.DepartmentID, (d, s) =>
                           new DepSecViewModel { department = d, section = s }).OrderBy(i => i.department.Name).ThenBy(i => i.section.Name);
        return Json(await DepSec.ToListAsync());
    }

和View模型如下

 public class DepSecViewModel
{
    public Department department { get; set; }
    public Section section { get; set; }

}

0 个答案:

没有答案