AJAX调用后返回Partial View为null 分部视图无法渲染更新
修复步骤
- 1. 修正AJAX请求类型与后端接口的匹配问题
你的后端接口加了[HttpPost]注解,但前端AJAX里强制指定了type: "GET",GET请求无法匹配POST接口,且GET请求不会读取请求体里的JSON数据,会直接导致请求失败/参数为空。
修改前端JS的AJAX配置,把请求类型改回POST即可:
function getTrainer_New(selectObject) { var values = selectObject.value; var FilterTagInfo = {}; FilterTagInfo.FilterTagID = ""; FilterTagInfo.Name = "TEST"; FilterTagInfo.TrainerName = document.getElementById("selectTrainer").value; FilterTagInfo.CategoryID = "MyCategory"; $.ajax({ url: "@Url.Action("FilterTrainerName", "Dashboard")", data: JSON.stringify(FilterTagInfo), type: "POST", // 改回POST,和后端注解匹配 async: true, dataType: 'html', contentType: "application/json; charset=utf-8", success: function (data) { $("#dvResultTrainer").html(data); // 直接用data,不要加.responseText }, error: function (xhr) { alert("Error" + xhr.responseText); $("#dvResultTrainer").html(xhr.responseText); } }); }
- 2. 修正success回调的返回值读取逻辑
你指定了dataType: 'html',请求成功后回调的第一个参数data直接就是返回的HTML字符串,没有responseText属性,responseText是错误回调里XHR对象的属性,你之前写data.responseText取到的就是undefined,所以渲染出来是空的,上述JS代码已经同步修正了这一点。 - 3. 分部视图可选优化(避免ViewBag为空异常)
可以把分部视图改成直接读取传入的模型,不用依赖ViewBag,稳定性更高:
后端控制器代码:
[HttpPost] public async Task<PartialViewResult> FilterTrainerName([FromBody] FilterTagInfo filterTagInfo) { // 保留原有查询逻辑 var finalresult = 你的查询结果; return PartialView("_PartialTrainer", finalresult.ToList()); }
分部视图代码:
@model List<FilterTagInfo> <ejs-chiplist id="filterTags" selection="Single" click="Filters"> <e-chips> @foreach (var p in Model) { <e-chip text="@p.Name" value="@p.ID" enabled="true"></e-chip> } </e-chips> </ejs-chiplist>
做完以上修改后,下拉切换即可正常渲染分部视图内容。
内容的提问来源于stack exchange,提问作者Shweta Tiwari
相关产品推荐
相关产品推荐

