如何在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
相关产品推荐
相关产品推荐

