Javascript数组indexOutOfRange在C#controller中循环时

时间:2016-11-09 10:29:37

标签: javascript c# jquery arrays

编辑2 我意外地传达了异常是IndexOutOfBounds类型,但它实际上是IndexOutOfRange类型。

我正在尝试将一些对象保存到服务器。这些是采取的行动:

  1. javascript数组是Text对象的数组。
  2. 这些Text对象在传输到控制器时放在TextModel列表中。 (通过使用JQuery.Post)
  3. 然后需要将TextModels列表中的每个元素放入一个新的服务器对象TextInfo。
  4. 每个TextInfo对象都放入一个存储在PageInfo对象中的新数组
  5. 将PageInfo对象发送到服务器进行进一步处理。
  6. #3上的过程错误。出于某种原因,我在循环遍历TextModel列表时得到IndexOutOfRange异常。将所有TextModel列表元素添加(循环)到新的TextInfo列表后,出现错误。这当它试图增加for循环计数器(i)时。我希望它增加i然后在条件不满足时退出循环,但它似乎在i ++上出错。

    我不知道是什么导致了这个错误。如代码所示,我只使用列出的对象来填充新对象的属性,我不会尝试在循环中编辑属性。任何可能导致问题的见解都会有所帮助。提前谢谢。

    修改1

    显然这还不够清楚。所有随帖子发送的对象都按预期在控制器中接收。 Count始终保持预期的元素数量,并且所有元素都已正确设置。请参阅JSON示例&图1有关详细信息。

    Javascript(#1)中定义的文本对象

    function Text() {
        //this.Id = 0;
        this.text = "Hallo";
        this.x = 0;
        this.y = 0;
        this.fillColor = "black";
        this.fontFamily = "Arial";
        this.fontStyle = "normal";
        this.fontSize = "18pt";
        this.fontWeight = "normal";
        this.textAlignment = "start";
        this.angle = 0;
    }
    function addText(text, fillColor, fontSize, fontFamily, fontStyle, fontWeight, textAlignment, x, y, angle) {
        var textTemp = new Text;
        textTemp.text = multilineText(text, fontSize, fontFamily, fontStyle);
    
        textTemp.fillColor = fillColor;
        textTemp.fontSize = fontSize;
        textTemp.fontFamily = fontFamily;
        textTemp.fontWeight = fontWeight;
        textTemp.fontStyle = fontStyle;
        textTemp.x = x;
        textTemp.y = y;
        textTemp.textAlignment = textAlignment;
        textTemp.angle = angle;
    
        textObjects.push(textTemp);
    }
    

    Javascript JQuery.Post&控制器中的TextModel(#2)

    // Saves page information 
    // Called on Save, Next / Previous Page.
    // @param curPageNum The currently selected page's number.
    function savePage(curPageNum) {
        var pageNumber = curPageNum;
    
        var json = JSON.stringify({ TextObjects: textObjects, ImageSource: imageSource, CurrentPageNumber: pageNumber });
        alert(json);
    
        $.ajax({
            url: "/NextprintPhotobook/SavePageInfo",
            type: "POST",
            data: json,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                console.log(data.message);
                showSuccess(data.message);
            },
            error: function (data) {
                console.log(data);
                showError("Er is een fout opgetreden bij het opslaan van de foto.");
            }
    
        });
    }
    

    控制器(#3,#4)

    public ActionResult SavePageInfo(List<TextModel> TextObjects, string ImageSource, int CurrentPageNumber)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    #region Define & initialize textInfoArray (Array of Textinfo objects)
                    // textInfoArray used to set property of the page info object.
                    TextInfo[] textInfoArray = null;
                    List<TextInfo> textInfoList = new List<TextInfo>();
                    if (TextObjects != null)
                    {
                        // Build textInfo list.
                        // textInfoList used to build a list from the TextObjects parameter.
                        for (int i = 0; i < TextObjects.Count; i++)
                        {
                            TextModel textObject = TextObjects[i];
                            PositionInfo positionInfo = null;
                            if (textObject.x >= 0 && textObject.y >= 0)
                            {
                                int xTemp = textObject.x;
                                int yTemp = textObject.y;
                                positionInfo = new PositionInfo()
                                {
                                    X = xTemp,
                                    Y = yTemp
                                };
                            }
                            string textTemp = textObject.text;
                            string fontFamilyTemp = textObject.fontFamily;
                            string fontSizeTemp = textObject.fontSize;
                            string fontWeightTemp = textObject.fontWeight;
                            string fontStyleTemp = textObject.fontStyle;
                            string fillColorTemp = textObject.fillColor;
                            int rotationTemp = textObject.angle;
                            string alignmentTemp = textObject.textAlignment;
                            TextInfo textInfo = new TextInfo()
                            {
                                Value = textTemp,
                                Font = fontFamilyTemp,
                                Size = fontSizeTemp,
                                Weight = fontWeightTemp,
                                Style = fontStyleTemp,
                                Color = fillColorTemp,
                                Rotation = rotationTemp,
                                Position = positionInfo,
                                Alignment = alignmentTemp
                            };
                            textInfoList.Add(textInfo);
                        }
                        textInfoArray = textInfoList.ToArray();
                    }
    
                    #endregion
    
                    #region Define & initialize PageInfo
                    PageInfo pageInfo = null;
                    if (textInfoList == null)
                    {
                        return Json(new APIResponse { OK = 0, message = "Er is een onbekende fout opgetreden binnen de API." }, "text/html");
                    }
    
                    string fileName = "";
                    string tempSource = ImageSource;
                    fileName = this.getFileNameFromSource(tempSource);
    
                    if (fileName == null)
                    {
                        return Json(new APIResponse { OK = 0, message = "Er is een onbekende fout opgetreden binnen de API." }, "text/html");
                    }
                    if (CurrentPageNumber <= 0)
                    {
                        return Json(new APIResponse { OK = 0, message = "Er is een onbekende fout opgetreden binnen de API." }, "text/html");
                    }
                    pageInfo = new PageInfo()
                    {
                        PageNumber = CurrentPageNumber,
                        FileName = fileName,
                        Text = textInfoArray
                    };
                    #endregion
    
                    client.BaseAddress = new Uri(SERVER_URI);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
    
                    HttpResponseMessage response = client.PostAsJsonAsync<PageInfo>("api/Xml/SavePageInfo?hash=" + SecurityHash + "&collectionId="
                        + CollectionId + "&version=" + Version, pageInfo).Result;
    
                    if (response.IsSuccessStatusCode)
                    {
                        APIResponse apiResponse = response.Content.ReadAsAsync<APIResponse>().Result;
    
                        Logger.log("API response received, see API log for more details.");
    
                        return Json(apiResponse, "text/html");
                    }
                    else
                    {
                        throw new Exception(response.ReasonPhrase);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.log("An exception occurred while saving page info: {0}", e.Message);
                return Json(new APIResponse { OK = 0, message = "Er is een onbekende fout opgetreden bij het communiceren met de API." }, "text/html");
            }
        }
    

    JSON示例 这是发送的JSON:

      

    [{ “TextObjects”:[{ “文本”:“测试   ”, “×”:50, “Y”:50, “填充颜色”: “#77DD44”, “fontFamily中”: “Arial字体”, “fontStyle”: “正常”, “fontSize的”: “18pt”, “fontWeight设置” : “正常”, “textAlignment”: “启动”, “角度”:0}], “ImageSource的”: “http://localhost:22223//Cyber/1718/1/img/resized/1.jpg”, “CurrentPageNumber”:1}]

    C# received object

0 个答案:

没有答案