Episerver中AJAX调用时如何传递当前Block到控制器
实现方案说明
HTTP 协议本身是无状态的,首次页面渲染时生成的 ABCBlock 实例是服务器端的临时对象,不会自动保留到后续的 AJAX 请求中,因此直接在参数中声明 ABCBlock 类型必然会得到 null 值,可通过以下两种方案实现需求:
方案1:传递Block唯一标识,服务端重新加载(推荐)
适合 Block 为 CMS 系统(如 Optimizely/Episerver)中已存储的内容块场景,操作步骤如下:
- 在 Block 对应的 Razor 视图中,将 Block 的唯一 ID 输出到 JS 变量或者隐藏域:
<script> // 也可存储在隐藏input标签中,按需选择即可 window.currentBlockId = '@Model.ContentLink.ID'; </script>
- 修改 AJAX 请求,将 Block ID 和国家 ID 一同传递:
$.ajax({ type: "GET", url: "/dummycontroller/getstates/", data: { countryid: countrid, blockId: window.currentBlockId }, success: (res) => { // 处理返回的州/省列表数据 }, error: () => { // 异常处理逻辑 } });
- 控制器端接收 ID 后,加载对应 Block 实例:
// 依赖注入IContentLoader,框架自带无需额外引入 private readonly IContentLoader _contentLoader; public DummyController(IContentLoader contentLoader) { _contentLoader = contentLoader; } [HttpGet] public virtual ActionResult GetStates(int blockId, string countryid) { ABCBlock currentBlock = null; if(_contentLoader.TryGet<ABCBlock>(new ContentReference(blockId), out currentBlock)) { // 此处可正常获取currentBlock的所有属性值,完成数据过滤逻辑 } // 返回处理后的州/省列表 }
方案2:序列化Block自定义字段传递
如果 Block 中的过滤数据是临时计算生成,未存储在 CMS 内容属性中,无法通过 ID 重新加载,可以采用该方案:
- 在 Razor 视图中将需要用到的 Block 字段序列化为 JS 对象:
<script> window.blockFilterParams = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(new { FilterRule1 = Model.CustomFilterRule1, FilterRule2 = Model.CustomFilterRule2 // 按需列出所有需要用到的字段即可 })); </script>
- 修改 AJAX 请求传递参数对象:
$.ajax({ type: "POST", // 参数较多时建议用POST避免GET长度限制 url: "/dummycontroller/getstates/", data: { countryid: countrid, filterParams: window.blockFilterParams }, success: (res) => { // 处理返回数据 }, error: () => { } });
- 控制器端接收参数:
// 定义接收参数的DTO类,字段和前端序列化字段对应 public class BlockFilterParams { public string FilterRule1 { get; set; } public int FilterRule2 { get; set; } } [HttpPost] public virtual ActionResult GetStates(BlockFilterParams filterParams, string countryid) { // 直接使用filterParams中的参数完成过滤逻辑即可 }
注意事项
- GET 请求传递参数有长度限制,复杂参数场景建议统一使用 POST 请求
- 不要直接序列化整个 Block 实例传递,会有大量冗余数据,也存在序列化失败的风险
内容的提问来源于stack exchange,提问作者Ms1
相关产品推荐
相关产品推荐

