ASP.NET MVC Core中如何刷新ViewComponent默认视图的数据
问题解决步骤
1. 修复工作卡片的数据属性绑定
首先,主视图中未给工作卡片添加data-job属性,导致点击时无法获取工作数据。需在循环生成卡片时添加该属性:
@{ int count = 0; } <!-- 先声明count变量 --> @foreach (var listing in Model) { <div id="listing-@count" class="list-group-item list-group-item-action" data-bs-toggle="list" href="#listing-@count" data-job='@Html.Raw(Json.Serialize(listing))'> <!-- 序列化工作对象到data属性 --> <!-- 工作卡片内容 --> </div> count++; }
注意使用单引号包裹
data-job值,避免与JSON内部的双引号冲突。
2. 修正Controller中ViewComponent的渲染逻辑
当前Action直接返回ViewComponentResult对象,无法被JSON序列化。需将ViewComponent渲染为HTML字符串后再返回:
private readonly IViewComponentHelper _viewComponentHelper; // 构造函数注入IViewComponentHelper public HomeController(IViewComponentHelper viewComponentHelper) { _viewComponentHelper = viewComponentHelper; } [HttpGet] public async Task<IActionResult> LoadJobDetail(string job) { JobListing jobDetail = JsonConvert.DeserializeObject<JobListing>(job); if (jobDetail != null) { // 渲染ViewComponent为HTML字符串 var componentResult = await _viewComponentHelper.InvokeAsync("JobDetail", new { jobListing = jobDetail }); using var writer = new StringWriter(); componentResult.WriteTo(writer, HtmlEncoder.Default); string renderedHtml = writer.ToString(); return Json(new { response = renderedHtml, success = true, message = "Job detail successfully loaded" }); } else { return Json(new { response = "", success = false, message = "could not load the selected job listing" }); } }
3. 完善AJAX的成功回调逻辑
在AJAX成功后,将返回的HTML字符串替换右侧详情区域的内容:
function LoadJobDetail(jobListing) { $.ajax({ type: "GET", url: "customer/Home/LoadJobDetail", data: { job: jobListing }, // jobListing已是JSON字符串,无需再次序列化 success: function (response) { if (response.success) { // 替换详情区域内容 document.getElementById('jobDetail').innerHTML = response.response; } else { console.error(response.message); } }, error: function (error) { console.log("operation failed...", error); } }); }
4. 确认ViewComponent视图的模型绑定
确保JobDetail组件的默认视图(Views/Shared/Components/JobDetail/Default.cshtml)顶部声明了正确的模型:
@model JobListing <!-- 此处编写工作详情的HTML渲染逻辑,使用Model访问属性 -->
以上步骤完成后,点击左侧工作卡片时,右侧详情区域会正确刷新为选中工作的内容。
内容的提问来源于stack exchange,提问作者emile keen
相关产品推荐
相关产品推荐

