最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - FormData has values but received on the endpoint as null, why? - Stack Overflow

programmeradmin7浏览0评论
   let itemIndex = 0, goalIndex = 0;
tableCollection.forEach((table) => {   
    //GOALS
    const thead = table.querySelector("thead");
    const tr = thead.querySelector(".top-header"); 
    const uid = table.getAttribute("data-bs-temp-id"); 
    const goalID = table.getAttribute("data-bs-goal-id"); 
    if (tr) { 
        const categoryID = tr.getAttribute("data-bs-category-id");
        const goalName = tr.querySelector('input[data-bs-column="GoalName"]');
        const percentageTD = tr.querySelector('input[data-bs-column="Percentage"]');
        const isItemsAutoCompute = tr.querySelector('input[data-bs-column="IsItemsAutoCompute"]'); 

        if (goalName && percentageTD && isItemsAutoCompute) { 
            const percentage = percentageTD.value.replace("%", '').trim(); 
            const category = categories.find(x => x.CategoryID == categoryID);
            const performanceID = category && category.IsForAll ? 0 : (parseInt(hdperformanceID.value) || 0); 
            const itemAuto = isItemsAutoCompute?.checked ?? false;


            formData.append(`vm.Goals[${goalIndex}].TempID`, uid || '');
            formData.append(`vm.Goals[${goalIndex}].GoalID`, parseInt(goalID) || 0);
            formData.append(`vm.Goals[${goalIndex}].PerformanceID`, performanceID);
            formData.append(`vm.Goals[${goalIndex}].CategoryID`, parseInt(categoryID) || 0);
            formData.append(`vm.Goals[${goalIndex}].GoalName`, goalName.value);
            formData.append(`vm.Goals[${goalIndex}].GoalPercentage`, parseFloat(percentage || 0));
            formData.append(`vm.Goals[${goalIndex}].IsItemsAutoCompute`, itemAuto);

            goalIndex+=1;
        }
    } 

    //ITEMS// 
    let Items = [];
    const tbody = table.querySelector("tbody");
    if (tbody) { 
        const tRows = tbody.querySelectorAll("tr"); 
        tRows.forEach((row) => {
            const itemID = parseInt(row.getAttribute("data-bd-item-id")) || 0;
            const iUid = row.getAttribute("data-bd-temp-item-id") || "";
            formData.append(`vm.Items[${itemIndex}].ParentTempID`, uid);
            formData.append(`vm.Items[${itemIndex}].TempItemID`, iUid);
            formData.append(`vm.Items[${itemIndex}].GoalID`, parseInt(goalID) || 0);
            formData.append(`vm.Items[${itemIndex}].ItemID`, itemID);

            if (columns) {
                for (const column of columns) {
                    let colName = column?.ColumnName?.trim();
                    if (colName) {
                        const data = row.querySelector(`td[data-bs-column="${colName}"]`);
                        if (!data) continue;


                        colName = colName.toLowerCase();

                        switch (colName) {
                            case "itemname": 
                                    if (!data.textContent.trim()) {
                                        goSave = false;
                                        message = "Please enter the item name.";
                                        data.focus();
                                        return;
                                    }
                                    formData.append(`vm.Items[${itemIndex}].ItemName`, data.textContent.trim()); 
                                break;

                            case "itemweight":
                                if (!itemauto && !data.textContent.trim()) {
                                    goSave = false;
                                    message = "Please enter the item weight.";
                                    data.focus();
                                    return;
                                }
                                const itemWeight = parseFloat(data.textContent.replace("%", "").trim()) || 0;
                                formData.append(`vm.Items[${itemIndex}].ItemWeight`, itemWeight);
                                break;

                            case "unit":
                                const select = data.querySelector("select");
                                if (select) {
                                    if (select?.value <= 0) {
                                        goSave = false;
                                        message = "Please select a unit!";
                                        select.focus();
                                        return;
                                    }
                                    formData.append(`vm.Items[${itemIndex}].UnitID`, parseInt(select.value) || 0);
                                }
                                break;

                            case "consolidated":
                                //if (configuration?.KRAEnabled && !data.textContent.trim()) {
                                //    goSave = false;
                                //    message = "Please enter the consolidated target.";
                                //    data.focus();
                                //    return;
                                //}
                                if (configuration.IsOngoing && configuration.KRAEnabled) {
                                    formData.append(`vm.Items[${itemIndex}].Consolidated`, data.textContent.trim());
                                }   
                                break; 
                            case "result": 
                                    formData.append(`vm.Items[${itemIndex}].Result`, data.textContent.trim() || ""); 
                                break; 
                            case "ratio": 
                                    const checked = data.querySelector("input");
                                    formData.append(`vm.Items[${itemIndex}].Ratio`, checked?.checked || false);  
                                break;
                            default: 
                                if (colName.includes("-tgt") || colName.includes("-rst")) {
                                    if (companies && companies.length > 0) {
                                        companies.forEach((company, cIndex) => {
                                            const companyName = company.CompanyName.toLowerCase().replace(/\s+/g, '');
                                            if (colName.includes(companyName)) {  
                                                formData.append(`vm.Items[${itemIndex}].CompanyTargets[${cIndex}].CompanyID`, company.CompanyID.toString()); 
                                                formData.append(`vm.Items[${itemIndex}].CompanyTargets[${cIndex}].ItemID`, itemID); 

                                                if (configuration.IsOngoing && configuration.KRAEnabled) {
                                                    if (colName.toLowerCase().includes("-tgt")) {
                                                        formData.append(`vm.Items[${itemIndex}].CompanyTargets[${cIndex}].Target`, data.textContent || "");
                                                    } 
                                                } else if (configuration.IsOngoing && configuration.AppraisalEnabled) {
                                                    if (colName.toLowerCase().includes("-rst")) {
                                                        formData.append(`vm.Items[${itemIndex}].CompanyTargets[${cIndex}].Result`, data.textContent || "");
                                                    }
                                                }
                                            }
                                        });
                                    }
                                } 
                                break;
                        }
                    }
                }
            }

            const actionData = row.querySelector(`td[data-bs-column="Action"]`);
            if (actionData) {
                const uploadElement = actionData.querySelector("input[type='file']");
                if (uploadElement?.files?.length > 0) {
                    Array.from(uploadElement.files).forEach((file) => {
                        formData.append(`vm.Items[${itemIndex}].Attachments`, file);
                    });
                }
            }

            itemIndex++;
        });
    } 
});


 [HttpPost, Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
 public async Task<IActionResult> JSUpdateEvaluationItems([FromForm]PerformanceViewerViewModel vm)
 { 
     var result = await performanceRepository.UpdateEvaluationItems(vm);
     return Json(result.ToString());
 }

This is my code to append my data to form data and will be sent to an endpoint.

I checked my formData, and it has values. yet when received on the endpoint, the parameter vm is null.

As I investigated, When I removed this part of code

formData.append(vm.Items[${itemIndex}].CompanyTargets[${cIndex}].CompanyID, company.CompanyID);

The vm has values.

What could be the possible reason of this and how can I fix this

EDIT: I added the whole processing of the data of tableCollections.

   let itemIndex = 0, goalIndex = 0;
tableCollection.forEach((table) => {   
    //GOALS
    const thead = table.querySelector("thead");
    const tr = thead.querySelector(".top-header"); 
    const uid = table.getAttribute("data-bs-temp-id"); 
    const goalID = table.getAttribute("data-bs-goal-id"); 
    if (tr) { 
        const categoryID = tr.getAttribute("data-bs-category-id");
        const goalName = tr.querySelector('input[data-bs-column="GoalName"]');
        const percentageTD = tr.querySelector('input[data-bs-column="Percentage"]');
        const isItemsAutoCompute = tr.querySelector('input[data-bs-column="IsItemsAutoCompute"]'); 

        if (goalName && percentageTD && isItemsAutoCompute) { 
            const percentage = percentageTD.value.replace("%", '').trim(); 
            const category = categories.find(x => x.CategoryID == categoryID);
            const performanceID = category && category.IsForAll ? 0 : (parseInt(hdperformanceID.value) || 0); 
            const itemAuto = isItemsAutoCompute?.checked ?? false;


            formData.append(`vm.Goals[${goalIndex}].TempID`, uid || '');
            formData.append(`vm.Goals[${goalIndex}].GoalID`, parseInt(goalID) || 0);
            formData.append(`vm.Goals[${goalIndex}].PerformanceID`, performanceID);
            formData.append(`vm.Goals[${goalIndex}].CategoryID`, parseInt(categoryID) || 0);
            formData.append(`vm.Goals[${goalIndex}].GoalName`, goalName.value);
            formData.append(`vm.Goals[${goalIndex}].GoalPercentage`, parseFloat(percentage || 0));
            formData.append(`vm.Goals[${goalIndex}].IsItemsAutoCompute`, itemAuto);

            goalIndex+=1;
        }
    } 

    //ITEMS// 
    let Items = [];
    const tbody = table.querySelector("tbody");
    if (tbody) { 
        const tRows = tbody.querySelectorAll("tr"); 
        tRows.forEach((row) => {
            const itemID = parseInt(row.getAttribute("data-bd-item-id")) || 0;
            const iUid = row.getAttribute("data-bd-temp-item-id") || "";
            formData.append(`vm.Items[${itemIndex}].ParentTempID`, uid);
            formData.append(`vm.Items[${itemIndex}].TempItemID`, iUid);
            formData.append(`vm.Items[${itemIndex}].GoalID`, parseInt(goalID) || 0);
            formData.append(`vm.Items[${itemIndex}].ItemID`, itemID);

            if (columns) {
                for (const column of columns) {
                    let colName = column?.ColumnName?.trim();
                    if (colName) {
                        const data = row.querySelector(`td[data-bs-column="${colName}"]`);
                        if (!data) continue;


                        colName = colName.toLowerCase();

                        switch (colName) {
                            case "itemname": 
                                    if (!data.textContent.trim()) {
                                        goSave = false;
                                        message = "Please enter the item name.";
                                        data.focus();
                                        return;
                                    }
                                    formData.append(`vm.Items[${itemIndex}].ItemName`, data.textContent.trim()); 
                                break;

                            case "itemweight":
                                if (!itemauto && !data.textContent.trim()) {
                                    goSave = false;
                                    message = "Please enter the item weight.";
                                    data.focus();
                                    return;
                                }
                                const itemWeight = parseFloat(data.textContent.replace("%", "").trim()) || 0;
                                formData.append(`vm.Items[${itemIndex}].ItemWeight`, itemWeight);
                                break;

                            case "unit":
                                const select = data.querySelector("select");
                                if (select) {
                                    if (select?.value <= 0) {
                                        goSave = false;
                                        message = "Please select a unit!";
                                        select.focus();
                                        return;
                                    }
                                    formData.append(`vm.Items[${itemIndex}].UnitID`, parseInt(select.value) || 0);
                                }
                                break;

                            case "consolidated":
                                //if (configuration?.KRAEnabled && !data.textContent.trim()) {
                                //    goSave = false;
                                //    message = "Please enter the consolidated target.";
                                //    data.focus();
                                //    return;
                                //}
                                if (configuration.IsOngoing && configuration.KRAEnabled) {
                                    formData.append(`vm.Items[${itemIndex}].Consolidated`, data.textContent.trim());
                                }   
                                break; 
                            case "result": 
                                    formData.append(`vm.Items[${itemIndex}].Result`, data.textContent.trim() || ""); 
                                break; 
                            case "ratio": 
                                    const checked = data.querySelector("input");
                                    formData.append(`vm.Items[${itemIndex}].Ratio`, checked?.checked || false);  
                                break;
                            default: 
                                if (colName.includes("-tgt") || colName.includes("-rst")) {
                                    if (companies && companies.length > 0) {
                                        companies.forEach((company, cIndex) => {
                                            const companyName = company.CompanyName.toLowerCase().replace(/\s+/g, '');
                                            if (colName.includes(companyName)) {  
                                                formData.append(`vm.Items[${itemIndex}].CompanyTargets[${cIndex}].CompanyID`, company.CompanyID.toString()); 
                                                formData.append(`vm.Items[${itemIndex}].CompanyTargets[${cIndex}].ItemID`, itemID); 

                                                if (configuration.IsOngoing && configuration.KRAEnabled) {
                                                    if (colName.toLowerCase().includes("-tgt")) {
                                                        formData.append(`vm.Items[${itemIndex}].CompanyTargets[${cIndex}].Target`, data.textContent || "");
                                                    } 
                                                } else if (configuration.IsOngoing && configuration.AppraisalEnabled) {
                                                    if (colName.toLowerCase().includes("-rst")) {
                                                        formData.append(`vm.Items[${itemIndex}].CompanyTargets[${cIndex}].Result`, data.textContent || "");
                                                    }
                                                }
                                            }
                                        });
                                    }
                                } 
                                break;
                        }
                    }
                }
            }

            const actionData = row.querySelector(`td[data-bs-column="Action"]`);
            if (actionData) {
                const uploadElement = actionData.querySelector("input[type='file']");
                if (uploadElement?.files?.length > 0) {
                    Array.from(uploadElement.files).forEach((file) => {
                        formData.append(`vm.Items[${itemIndex}].Attachments`, file);
                    });
                }
            }

            itemIndex++;
        });
    } 
});


 [HttpPost, Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
 public async Task<IActionResult> JSUpdateEvaluationItems([FromForm]PerformanceViewerViewModel vm)
 { 
     var result = await performanceRepository.UpdateEvaluationItems(vm);
     return Json(result.ToString());
 }

This is my code to append my data to form data and will be sent to an endpoint.

I checked my formData, and it has values. yet when received on the endpoint, the parameter vm is null.

As I investigated, When I removed this part of code

formData.append(vm.Items[${itemIndex}].CompanyTargets[${cIndex}].CompanyID, company.CompanyID);

The vm has values.

What could be the possible reason of this and how can I fix this

EDIT: I added the whole processing of the data of tableCollections.

Share Improve this question edited Jan 15 at 15:53 mat mat asked Jan 15 at 15:44 mat matmat mat 234 bronze badges 3
  • 2 formData.append(vm.Items[${itemIndex}].ParentTempID, uid) gives a syntax error in Javascript (Unexpected token '{'). What programming language is that (since you mention the c# tag)? – Heiko Theißen Commented Jan 15 at 15:50
  • Perhaps you mean formData.append(`vm.Items[${itemIndex}].CompanyTargets[${cIndex}].CompanyID`, company.CompanyID); formData.append(`vm.Items[${itemIndex}].CompanyTargets[${cIndex}].ItemID`, itemID); – mplungjan Commented Jan 15 at 15:53
  • @HeikoTheißen please check, i added the whole code. I added the c# tag because I have appended the endpoint of the c# – mat mat Commented Jan 16 at 4:00
Add a comment  | 

1 Answer 1

Reset to default 0

so basically, the code in javascript is not the problem. its the size of formdata that will be sent on the endpoint.

in my Program.cs

// Configure large file upload limits for Kestrel
builder.Services.Configure<FormOptions>(options =>
{
    options.ValueCountLimit = int.MaxValue; // Set the desired value (default is 1024)
    options.ValueLengthLimit = int.MaxValue; // No limit for form value length
    options.MultipartBodyLengthLimit = 1 * 1024 * 1024 * 1024; // 1 GB
});

I added the options.ValueCountLimit = int.MaxValue;. As I saw the problem is the default value of options.ValueCountLimit = 1024

and it worked.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论