获取空对象数组jquery post

Posted

技术标签:

【中文标题】获取空对象数组jquery post【英文标题】:Getting Null object array jquery post 【发布时间】:2017-03-23 23:58:46 【问题描述】:

我是 Angular.js 框架的新手。我正在获取使用角度范围进一步分配给数组的数据。

Modal.CS:

 public class AppSetting1

    public int lng_AppSettings  get; set; 
    public string str_SettingName  get; set; 
    public string str_SettingValue  get; set; 
    public string str_Type  get; set; 

    public AppSetting1(int _lng_AppSettings, string _str_SettingName, string _str_SettingValue, string _str_Type)
    
        lng_AppSettings = _lng_AppSettings;
        str_SettingName = _str_SettingName;
        str_SettingValue = _str_SettingValue;
        str_Type = _str_Type;
    


 internal string GetAppSettings()
        
            try
            

                    List<AppSetting1> objAppsettings = new List<AppSetting1>();
                    objAppsettings.Add(new AppSetting1(1,"Name1","Value1","Type"));
                    objAppsettings.Add(new AppSetting1(2, "Name2", "Value2", "Type2"));
                    return JsonConvert.SerializeObject(objAppsettings, Formatting.Indented, new JsonSerializerSettings  ReferenceLoopHandling = ReferenceLoopHandling.Ignore );

            
            catch (Exception ex)
            
                throw ex;
            
        

Controller.CS:

   [AuthCheckService, SessionCheckService]
    [HandleModelStateException]
    public string GetAppSettings()
    
        try
        
           ManageAppSettings accExec = new ManageAppSettings();
           return accExec.GetAppSettings();
        
        catch (Exception ex)
        
            throw new ModelStateException(ex.Message, ex.InnerException);
        
    

    [HttpPost]
    public JsonResult SaveSettings(List<AppSetting1> AppSetting)
    
        try
        
            ManageAppSettings accExec = new ManageAppSettings();
            return Json(AppSetting, JsonRequestBehavior.AllowGet);
        
        catch (Exception ex)
        
            throw new ModelStateException(ex.Message, ex.InnerException);
        
    

Angular.js:

(function () 
var app = angular.module('myAppSeetings', []);
app.controller('AppSettingsController', function ($scope) 

    $scope.items = [];
    $scope.SaveSettings = function () 
        if (validate()) 
            var token = $('[name=__RequestVerificationToken]').val();
            var test = $scope.items;
            $.ajax(
                beforesend: showProgress(),
                type: 'POST',
                headers:  "__RequestVerificationToken": token ,
                url: getAppPath() + 'AppSettings/SaveSettings',
                dataType: 'json',
                data:  AppSetting: $scope.items ,
                success: function (result) 
                    if (result != "") 
                        //ShowSaveMessage(result);
                        //fetchData();
                        //$('#EditPopUp').css('display', 'none');
                        //$('#exposeMaskManageUser').css('display', 'none');
                        //clearForm();
                    
                    else
                        ShowErrorPopup('An error has occurred. Please contact System Administrator.');
                ,
                complete: hideProgress,
                error: function (ex) 
                    ShowErrorPopup('An error has occurred. Please contact System Administrator.');
                
            );
        
        else 
            ShowWarningMessage('Required fields must be completed prior to completing the work');
        
    ;

    function fetchData() 

        var token = $('[name=__RequestVerificationToken]').val();
        $.ajax(
            beforesend: showProgress(),
            type: 'GET',
            headers:  "__RequestVerificationToken": token ,
            url: getAppPath() + 'AppSettings/GetAppSettings',
            dataType: 'json',
            success: function (data) 
                // console.log(data);
                $scope.items = data;
                $scope.$apply();
                console.log($scope.items);
            ,
            complete: hideProgress,
            error: function (ex) 
                ShowErrorPopup('An error has occurred. Please contact System Administrator.');
            
        );
    ;

    function validate() 
        var val = true;
        if ($("input").val().trim() == "") 
            val = false;
        
        return val;
    
    fetchData();
);

)();

问题:

在保存单击时,我在服务器端得到空值。我哪里错了?

【问题讨论】:

我建议尽可能在 angularjs 中使用XMLHttpRequest,而不是$.ajax。使用方法链接:developer.mozilla.org/en-US/docs/Web/API/FormData/… 【参考方案1】:

尝试添加 contentType: 'application/json; charset=utf-8',

See this answer

【讨论】:

非常感谢达米安。我忘了添加这个:-)【参考方案2】:

你的代码错了:

data:  AppSetting: $scope.items 

应该是

data: $scope.items

在您的 saveClick 函数中:$scope.items 现在是 []。它应该具有您期望的一些值。取决于您的情况,它来自客户端或测试的默认值:

$scope.items = [lng_AppSettings: 1, str_SettingName : 'Name 1',
                lng_AppSettings: 2, str_SettingName : 'Name 2'];

【讨论】:

仍然为空 没什么,在服务器上,当我查看参数值时,它为空。在客户端,一切正常。那里没有异常或错误日志。 $scope.items 现在是空的。它应该有价值

以上是关于获取空对象数组jquery post的主要内容,如果未能解决你的问题,请参考以下文章

对象数组的 jQuery POST 到节点

jQuery 1.4.4+ AJAX 请求 - 发布空数组或对象变成字符串

Jquery获取已经选中的checkbox

jquery $.post 空数组

如何为 JSON Post 序列化 jQuery 对象数组?

jquery的$post方法不发送空数组的解决办法