使用ajax将列表发送到mvc控制器中

时间:2018-10-26 11:01:47

标签: c# ajax asp.net-mvc list

我有一个类似于以下内容的列表

List

我想将此列表发送到我的控制器中,

我正在使用ajax调用将数据从客户端发送到服务器端

这是我的ajax电话

    $.ajax({
        url: '/Main/updateTripundHoliday',
        data: d.weekendLeave,
        type: "GET",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (response) {

        }
    });

和我在控制器中的方法

    public bool updateHoliday(List<Holidaysclass> data)
    {
        for (var i = 0; i < data.Count(); i++)
        {
            insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
        }
        return true;
    }

我的List<Holidaysclass> data显示为空

我在这里可以做什么?

5 个答案:

答案 0 :(得分:1)

要将数据从浏览器发送到控制器,您需要使用POST类型,然后在ajax调用中传递data。您可以直接将您的entites映射为行动方法。

 $.ajax({
        url: '/Main/updateTripundHoliday',
        data: d.weekendLeave,
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (response) {

        }
    });

并在控制器中放入HttpPost数据注释

 [HttpPost]
 public bool updateHoliday(List<Holidaysclass> data)
    {
        for (var i = 0; i < data.Count(); i++)
        {
            insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
        }
        return true;
    }

答案 1 :(得分:0)

使用ajax get方法,我们不能将数据从客户端发送到服务器不是最好的方法。尝试使用POST方法将数据从客户端发送到服务器。

参考:https://api.jquery.com/jquery.post/

 $.ajax({
    url: '/Main/updateTripundHoliday',
    data: d.weekendLeave,
    type: "POST",
    ......
});

答案 2 :(得分:0)

您可以这样:

$(document).ready(function () {
    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];      

    things = JSON.stringify({ 'things': things });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 
});

请点击此链接以获取更多信息: https://materializecss.com/media.html

答案 3 :(得分:0)

您不能在获取请求中发布数据。相反,您需要使用POST类型的请求。 这是您的更新请求。

$.ajax({
        url: '/Main/updateTripundHoliday',
        data: d.weekendLeave,
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (response) {

        }
    });

此外,您的操作应带有[HttpPost]注释。

答案 4 :(得分:0)

尝试一下:

public pageReference getData(){
    date sd = date.parse(sDate).toStartOfWeek();
    date ed = date.parse(eDate);
    hList = new list<Hours__c>([SELECT Name,Employee__r.Id,Date_worked__c,Employee__r.Offshore__c,Employee__r.Name,Employee__r.Department__c,Employee_Name__c,hours__c,Minutes__c,Hours_Decimal__c FROM Hours__c WHERE Type_of_Hours__c = 'Work' AND Date_worked__c >= :sd AND Date_worked__c <= :ed AND Employee__r.Department__c IN :selected ORDER BY Employee__r.Department__c,Date_worked__c,Employee__r.Name LIMIT 3000]);
    wrap = new list<wrapper>();
    string tempDepartment;
    string tempEmpName;
    date tempWorkDate;
    date tempStart = sd;
    decimal offshore = 0;
    decimal onshore = 0;
    decimal totalOffshore = 0;
    decimal totalOnShore = 0;
    decimal dateCount = 0;
    decimal aggreagteTotal = 0;
    integer hitLimit = 3000;
    integer rpwp = 0;
    integer compareRPWP = 0;
    boolean fired = false;
    boolean dateChanged = false;
    boolean dateCountis13 = false;
    map<date,integer> mapDateCount = new map<date,integer>();
    if(hList.size() > 0 && hList.size() < hitLimit){
        noResults = false;
        for(Hours__c h: hList){
            //initiate a new wrapper for each department as a primary header
            if( (h.Employee__r.Department__c != null && ((tempDepartment != null && tempDepartment != h.Employee__r.Department__c) || ( tempDepartment == null)) ) ){
                fired = true;
                tempDepartment = h.Employee__r.Department__c;
                wrap.add(new wrapper(null,null,null,null,null,tempDepartment,'','','',null,'',''));
            }else{
                fired = false;
            }
            if(fired || dateCountis13){
                dateCountis13 = false;
                dateCount = 0;
                totalOffshore = 0;
                totalOnShore = 0;
            }
            //initiate a new wrapper for each new week period, total employee hours for each week period for each department
            if(fired || (h.Date_worked__c != null && ((tempWorkDate != null && tempWorkDate != h.Date_worked__c) || ( tempWorkDate == null)) ) || (h.Employee__r.Department__c != null && ((tempDepartment != null && tempDepartment != h.Employee__r.Department__c) || ( tempDepartment == null)) ) ){
                dateChanged = true;
                tempWorkDate = h.Date_worked__c;
                offshore = 0;
                onshore = 0;
                rpwp = 0;
                dateCount++;
                for(Hours__c h1: hList){
                    //get count of each record that is inside a given week period
                    if(h1.Date_worked__c == tempWorkDate && h1.Employee__r.Department__c == tempDepartment){
                        rpwp++;
                    }
                    //logic for totaling offshore hours by date and department
                    if(h1.Date_worked__c == tempWorkDate && h1.Employee__r.Offshore__c && h1.Employee__r.Department__c == tempDepartment){
                        offshore += h1.Hours_Decimal__c != null ? h1.Hours_Decimal__c : 0;
                    }
                    //logic for totaling onshore hours by date and department
                    if(h1.Date_worked__c == tempWorkDate && h1.Employee__r.Offshore__c == false && h1.Employee__r.Department__c == tempDepartment){
                        onshore += h1.Hours_Decimal__c != null ? h1.Hours_Decimal__c : 0;
                    }
                }
                system.debug('rpwp: ' + rpwp);
                wrap.add(new wrapper(h.Date_worked__c.toStartOfWeek(),h.Date_worked__c,onshore,offshore,null,'total','','','',null,'',''));
                totalOffshore += offshore;
                totalOnShore += onshore;
                system.debug('OffShore: ' +  offshore + '  ' + tempWorkDate.format());
                system.debug('OnShore: ' + onshore + '  ' + tempWorkDate.format());
            }else{
                dateChanged = false;
            }
            //initiate a new wrapper for each record and give the ability to open and collapse all records under a given total week period
            // functionality now does an aggregate total of employee's that have multiple hour entrees for each week period.
            if( dateChanged || (h.Employee__r.Name != null && ((tempEmpName != null && tempEmpName != h.Employee__r.Name) || ( tempEmpName == null)) ) ){
                tempEmpName = h.Employee__r.Name;
                aggreagteTotal = 0;
                for(Hours__c h2: hList){
                    if(tempEmpName == h2.Employee__r.Name && tempWorkDate == h2.Date_worked__c){
                        aggreagteTotal += h2.Hours_Decimal__c;
                    }
                }
                if(h.Employee__r.Offshore__c){
                    wrap.add(new wrapper(h.Date_worked__c.toStartOfWeek(),h.Date_worked__c,0,h.hours__c,aggreagteTotal,'collapse',h.Employee__r.Name,h.Employee__r.Id,h.Name,h.Employee__r.Offshore__c,h.Employee__r.Department__c,h.Date_worked__c.format() ));
                }else{
                    wrap.add(new wrapper(h.Date_worked__c.toStartOfWeek(),h.Date_worked__c,h.hours__c,0,aggreagteTotal,'collapse',h.Employee__r.Name,h.Employee__r.Id,h.Name,h.Employee__r.Offshore__c,h.Employee__r.Department__c,h.Date_worked__c.format() ));
                }
            }
            //compare record count on the outside loop to record count on the inner loop and set compare iterator to 0 if the date changes
            if(dateChanged){
                compareRPWP = 0;
            }
            compareRPWP++;
            system.debug('compareRPWP: ' +  compareRPWP );
            //if on the 13th week -- initiate a new wrapper and get quarterly totals -- compare record count so that inner loop matches outer loop
            if( (dateCount == 13 && compareRPWP == rpwp) ){
                system.debug('totalOffshore: ' +  totalOffshore );
                system.debug('totalOnShore: ' + totalOnShore );
                dateCountis13 = true;
                wrap.add(new wrapper(null,null,totalOnShore,totalOffshore,null,'quarter',tempDepartment,'','',null,'',''));
            }
        }
    }else if(hList.size() <= 0){
        noResults = true;
        bannerMessage = 'Oops! No record found.';
    }else if(hList.size() >= hitLimit){
        noResults = true;
        bannerMessage = 'Oops! 3000 Record limit hit.';
    }else{
        noResults = true;
        bannerMessage = 'Oops! 50000 record limit hit.';
    }

    system.debug('wrap: ' + wrap);
    system.debug('hList: ' + hList);
    return null;
}

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [NC,L]