首页 > 解决方案 > 控制器方法调用后不刷新 Razor 视图

问题描述

我的 Web 应用程序中有一个 Razor 视图,其中包含从 API 获取的数据。此视图中有一个下拉列表,在此下拉列表中选择一个条目会触发对我的 Web 应用程序控制器的 ajax 调用,并且该视图应通过此调用更新,但由于某种原因它不是。

当返回 View("Index", model); 到达时,模型对象内的数据已更改,但视图未使用此数据更新。当我使用浏览器中的按钮刷新页面时,视图会按预期更新。

ajax 调用调用的方法就是这个,它是从基本控制器继承的,这部分工作正常:

[HttpGet("abonnements/{idAbonnement}")]
public override async Task<IActionResult> UpdateAbonnementCourant(long idAbonnement)
{
    UpdateAbonnementCookie(idAbonnement);
    return await Index(idAbonnement);
}

UpdateAbonnementCourant 在同一个控制器中调用的 index 方法从 API 获取更新的数据,但不刷新视图:

[HttpGet("{idAbonnement?}")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None, Duration = 0)]
public async Task<IActionResult> Index(long? idAbonnement)
{
    if (!idAbonnement.HasValue && long.TryParse(HttpContext.Request.Cookies["idAbonnementSelectionne"], out long idAbonnementCookie))
        idAbonnement = idAbonnementCookie;

    string uri = ControllerContext.RouteData.Values["controller"].ToString();

    if (idAbonnement.HasValue)
        uri = $"{uri}/{idAbonnement}";

    HttpResponseMessage response = await _apiHttpClient.GetAsync(uri);

    if (response.IsSuccessStatusCode)
    {
        string json = await response.Content.ReadAsStringAsync();

        if (!string.IsNullOrEmpty(json))
        {
            var model = new HtmlModel
            {
                ContenuHtml = new HtmlString(json)
            };
            return View("Index", model);
        }
    }
    return View("Index");
}

它看起来像一个缓存问题,但 ResponseCache(NoStore = true) 没有解决问题。我不知道我错过了什么,我需要一些帮助。

标签: .netasp.net-core

解决方案


推荐阅读