You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kendo MultiSelect无法获取MVC控制器返回的配件总价问题求助

问题分析与解决方向

你的核心问题在于异步AJAX请求的处理逻辑错误:getPrice函数里的$.get是异步操作,当你在forEach里调用它时,函数会立刻返回初始的0,根本等不到后端返回真实的价格,所以total永远计算不对。下面是具体的解决步骤:

1. 修正异步请求的处理方式

把getPrice改成返回一个Promise,这样我们可以等待所有价格请求完成后再计算总价:

function getPrice(id, numberOfDays) {
    // 修正参数拼写错误(原代码里是numberOgDays,少了个r)
    return $.get('/Cars/GetAccessoriesPrice/?id=' + id + '&numberOfDays=' + numberOfDays, 'json');
}

2. 调整onChange函数的异步逻辑

使用Promise.all来批量处理所有配件的价格请求,等全部请求完成后再计算总价并更新UI:

function onChange(e) {
    var multiselect = $("#accessoriesCombo").data("kendoMultiSelect");
    var accessoriesLabel = $("#accessoriesLabel");
    var startDate = $("#rentStartPicker").data("kendoDateTimePicker").value();
    var endDate = $("#rentEndPicker").data("kendoDateTimePicker").value();
    var diffDay;
    if (calculate(startDate, endDate) < 1) {
        diffDay = calculate(startDate, endDate) + 1;
    } else {
        diffDay = calculate(startDate, endDate);
    }
    var arrayValues = this.value();
    
    // 生成所有价格请求的Promise数组
    const pricePromises = arrayValues.map(item => getPrice(item, diffDay));
    
    // 等待所有请求完成
    Promise.all(pricePromises)
        .then(prices => {
            // 拼接选中的配件ID文本
            const textValues = arrayValues.join(', ');
            // 计算总价(注意把返回的价格转为数字类型)
            const total = prices.reduce((sum, price) => sum + parseInt(price, 10), 0);
            accessoriesLabel.text(textValues + " (" + total + ")");
        })
        .catch(error => {
            // 处理请求失败的情况,比如提示用户
            console.error('获取配件价格失败:', error);
            accessoriesLabel.text('获取价格失败');
        });
}

3. 验证后端控制器的返回格式

确保你的GetAccessoriesPrice方法返回的是正确的JSON格式int值:

  • 如果是ASP.NET MVC:
public JsonResult GetAccessoriesPrice(int id, int numberOfDays)
{
    // 计算价格逻辑
    int price = // 你的计算代码;
    // 允许GET请求获取JSON(旧版MVC需要加JsonRequestBehavior.AllowGet)
    return Json(price, JsonRequestBehavior.AllowGet);
}
  • 如果是ASP.NET Core:
public IActionResult GetAccessoriesPrice(int id, int numberOfDays)
{
    int price = // 你的计算代码;
    return Json(price);
}

额外注意事项

  • 原代码里的numberOgDays是拼写错误,已经在getPrice里修正为numberOfDays,否则后端可能无法正确接收参数
  • 可以考虑给AJAX请求添加加载状态,比如在请求开始时显示“加载中”,提升用户体验
  • 如果配件数量较多,建议合并成一个批量请求(比如把所有ID传给后端一次计算总价),减少HTTP请求次数,提升性能

内容的提问来源于stack exchange,提问作者Patrik Volka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:58:26