You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core控制器修改模型值,AddCoin更新model.Balance返回0如何解决

问题原因
  • 你调用RedirectToAction后触发的是全新的HTTP请求,AddCoin方法中修改的model.Balance仅属于当前请求的上下文,不会传递到跳转后的Index接口,Index方法拿到的是全新初始化的HomeIndexViewModel实例,Balance默认值为0
  • 注释的私有balance字段不可用:ASP.NET Core中Controller默认是瞬态生命周期,每次请求都会创建新的Controller实例,两次请求的私有字段不属于同一个对象,存储的值无法跨请求读取。
解决方案

方案1:用TempData跨重定向传递值(适合仅本次跳转传递的场景)

TempData是ASP.NET Core专为跨重定向传值设计的存储机制,默认读取一次后自动销毁。

修改AddCoin方法

public ActionResult AddCoin(int value, HomeIndexViewModel model)
{
    var coin = coinManager.FindCoinById(value);
    // 如果硬币允许投入且售货机内硬币数量小于200
    if (coin.isAvailable == true && coin.NumberCoins < 200)
    {
        coin.NumberCoins += 1;
        // 读取已有余额,不存在则默认0
        var currentBalance = TempData["Balance"] as int? ?? 0;
        currentBalance += coin.Value;
        TempData["Balance"] = currentBalance;
        coinManager.SaveCoin(coin);
    };
    return RedirectToAction("Index");
}

修改Index方法

[HttpGet]
public ActionResult Index(HomeIndexViewModel model)
{
    model.Drinks = drinkManager.GetAllDrink();
    model.Coins = coinManager.GetAllCoin();
    // 读取TempData中的余额赋值
    model.Balance = TempData["Balance"] as int? ?? 0;
    // 如果需要后续请求继续使用余额,调用Keep方法避免TempData被销毁
    TempData.Keep("Balance");
    return View(model);
}

方案2:用Session存储(适合整个用户会话周期都需要保留余额的场景)

首先需要在Program.cs中开启Session配置:

// 添加到var app = builder.Build(); 之前
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30); // 会话超时时间
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

// 添加到app.UseAuthorization(); 之前
app.UseSession();

修改AddCoin方法

public ActionResult AddCoin(int value, HomeIndexViewModel model)
{
    var coin = coinManager.FindCoinById(value);
    if (coin.isAvailable == true && coin.NumberCoins < 200)
    {
        coin.NumberCoins += 1;
        var currentBalance = HttpContext.Session.GetInt32("Balance") ?? 0;
        currentBalance += coin.Value;
        HttpContext.Session.SetInt32("Balance", currentBalance);
        coinManager.SaveCoin(coin);
    };
    return RedirectToAction("Index");
}

修改Index方法

[HttpGet]
public ActionResult Index(HomeIndexViewModel model)
{
    model.Drinks = drinkManager.GetAllDrink();
    model.Coins = coinManager.GetAllCoin();
    model.Balance = HttpContext.Session.GetInt32("Balance") ?? 0;
    return View(model);
}
额外检查项

确认HomeIndexViewModel中的Balance属性为public修饰,否则模型绑定无法正常读取赋值:

public class HomeIndexViewModel
{
    public int Balance { get; set; }
    // 其他属性定义
}

内容的提问来源于stack exchange,提问作者Web FR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:57:03