如何将 ViewModel 对象添加到 TempData

How to add a ViewModel Object to TempData

我有以下带有视图模型的控制器 -

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Initiate(IFormCollection formCollection)
{
    var studentId = formCollection["studentid"].ToString();

    if (string.IsNullOrEmpty(studentId))
    {
        return NotFound(new { msg = "Unknown student" });
    }

    Student student = await _context.Students.Include(s=>s.Parents).FirstOrDefaultAsync(s=>s.Id==studentId).ConfigureAwait(false);

    var dashboard = User.FindFirstValue(ClaimTypes.Role).ToLower();

    if (formCollection["bill"].Count > 0)
    {
        //Calculate the total bills and present a payment confirmation page
        List<int> billIds = new List<int>();
        foreach (var id in formCollection["bill"])
        {
            billIds.Add(Convert.ToInt32(id));
        }

        if (billIds.Count > 0)
        {
            List<Fee> fees = await _context.Fees.Where(f => billIds.Contains(f.Id)).ToListAsync().ConfigureAwait(false);

            string CustomerEmail = null;
            string CustomerPhone = null;
            string CustomerFirstName = null;
            string CustomerLastName = null;

            if (student.Parents.Any())
            {
                var parent = student.Parents.FirstOrDefault();

                CustomerEmail = parent?.Email;
                CustomerPhone = parent?.PhoneNumber;
                CustomerFirstName = parent?.OtherNames;
                CustomerLastName = parent?.Surname;
            }
            string TrxnRef = RandomStringGenerator.UpperAlphaNumeric(5) + student.Id.Substring(0,8);

            BillsPayViewModel model = new BillsPayViewModel
            {
                StudentId=student.Id,
                StudentName=student.FullName,
                PaymentItems=fees,
                TransactionRef= TrxnRef,
                CustomerPhone = CustomerPhone ?? student.PhoneNumber,
                CustomerEmail = CustomerEmail ?? student.Email,
                CustomerFirstname = CustomerFirstName ?? student.OtherNames,
                CustomerLastname = CustomerLastName ?? student.Surname,
                CustomerFullname=$"{CustomerFirstName} {CustomerLastName}", 
                Currency = "NGN",
                AmountToPay=fees.Sum(a=>a.Amount),
                Callbackurl=$"/Payments/Status/{TrxnRef}"
            };

            TempData["PaymentDetails"] = model;
            return View("BillsPayConfirmation", model);
        }
    }
    else
    {
        TempData["msg"] = "<div class='alert alert-success'><i class='fa fa-check'></i> No outstanding bills found for student</div>";

        return RedirectToAction(dashboard, "dashboard");
    }
    return RedirectToAction();
}

我意识到,当我添加将模型添加到临时数据的部分时

TempData["PaymentDetails"] = model;

我得到以下内容

有没有办法将整个模型添加到 TempData,这样我就不需要在下一页重复生成 ViewModel 的过程?

您必须修复您的代码:

 Student student = await _context.Students.Include(s=>s.Parents).FirstOrDefaultAsync(s=>s.Id==studentId).ConfigureAwait(false);
if (student==null) ....return error
....
.....

if (student.Parents!=null &&  student.Parents.Count() > 0)
{
.....
}

 BillsPayViewModel model = new BillsPayViewModel
            {
                StudentId=student.Id,
                StudentName=student.FullName,
                PaymentItems=fees,
                TransactionRef= TrxnRef,
                CustomerPhone = CustomerPhone ?? student.PhoneNumber,
                CustomerEmail = CustomerEmail ?? student.Email,
                CustomerFirstname = CustomerFirstName ?? student.OtherNames,
                CustomerLastname = CustomerLastName ?? student.Surname,
                Currency = "NGN",
                AmountToPay=fees.Sum(a=>a.Amount),
                Callbackurl=$"/Payments/Status/{TrxnRef}"
            };

          model.CustomerFullname=  model.CustomerFirstName==null || model.CustomerLastName==null?
     string.Empty: $"{model.CustomerFirstName} {model.CustomerLastName}";

}
 

经过一番努力,我遇到了 这给了我一个问题的线索,结果发现问题是 TempData in ASP.NET Core (可能来自版本 5,因为我没有在其他版本中尝试过)没有包含对象的能力.

我试图将一个对象添加到 TempData,这就是问题的根源。而解决方法是先将模型序列化,再添加到TempData中,然后反序列化回我需要使用的对象,如下

  TempData["PaymentDetails"] = JsonConvert.SerializeObject(model);

然后在我需要的时候,反序列化如下

BillsPayViewModel paymentDetails = JsonConvert.DeserializeObject<BillsPayViewModel>((string)TempData["PaymentDetails"]);

我想这会为某人节省很多时间。