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

如何在NopCommerce中将Ajax返回数据设置到Nop Editor文本框

问题:NopCommerce 4.60.6中nop-editor赋值后无法立即显示

我正在使用NopCommerce 4.60.6,页面中使用了一个nop-editor文本框。点击按钮触发的Ajax请求能正常获取结果,但通过$("#TotalLabour").val(data);设置值后,结果并未立即显示在文本框中,仅当点击文本框聚焦后才会显示。

视图代码

<div class="form-group row">
    <div class="col-md-3">
        <nop-label asp-for="TotalLabour" />
    </div>
    <div class="col-md-9">
        <nop-editor asp-for="TotalLabour" />
        <input type="button" value="@T("Admin.Awaz.ClickForLabourAmount")" id="btn_getlabour" class="btn btn-primary" />                        
    </div>
</div>

Ajax代码

$(document).ready(function () {
    $('#btn_getlabour').bind('click', function () {            
        if (document.getElementById('NetWeight').value == 0) {
            alert("First Enter The NetWeight...!!!");
        }
        else {
            var postData = {
                netWeight: document.getElementById('NetWeight').value
            };
            $.ajax({
                cache: false,
                type: "GET",
                url: "@(Url.Action("GetLabourAmt"))",
                data: postData,
                success: function (data, textStatus, jqXHR) {                         
                    $("#TotalLabour").val(data);
                }
            });
        }
    });
});

后端控制器代码

public virtual async Task<IActionResult> GetLabourAmt(decimal netWeight)
{
    if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageCategories))
        return AccessDeniedView();            
    var labourPerGm = _labourMasterService.GetLabourAsync();
    var result = Convert.ToDecimal(labourPerGm.Result.Labour) * netWeight;
    return Json(result);
}

解决方案

nop-editor是NopCommerce封装的富文本编辑器(基于CKEditor),直接操作原生input的val()方法只会修改隐藏的表单字段,不会同步到编辑器的可视化界面,必须调用编辑器的官方API来设置内容。

修改Ajax的success回调部分代码即可:

success: function (data, textStatus, jqXHR) {                         
    // 获取CKEditor实例(id对应编辑器绑定的字段名TotalLabour)
    const editor = CKEDITOR.instances['TotalLabour'];
    if (editor) {
        // 将数值转为字符串后设置到编辑器
        editor.setData(data.toString());
        // 同步更新隐藏的input字段,确保表单提交时能获取到值
        $("#TotalLabour").val(data);
    } else {
        // 编辑器未加载时的降级处理
        $("#TotalLabour").val(data);
    }
}

注意事项:

  • 确保页面中CKEditor的脚本已正确加载,能正常获取到编辑器实例
  • 由于编辑器接收的是文本内容,需要把数字类型的data转为字符串再传入setData方法

内容的提问来源于stack exchange,提问作者s.k.Soni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:05:21