关于我的TempData["Something"]
,我遇到了问题,因为我想自定义Something
的每个内容。以下是我的代码:
控制器
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SaveLoanContract(ModelLoan lc, string message)
{
var myList = new ModelLoan();
var countLoan = _Context.LoanContract.Count(c => c.EmployeeId == lc.loanContract.EmployeeId && c.LoanTypeId == lc.loanContract.LoanTypeId);
if (ModelState.IsValid)
{
//Some Logic
TempData["SuccessMessage"] = new { CssClassName = "alert-success", Title = "Success!", Message = "You have successfully applied. Please wait for confirmation. Thank you!" };
return RedirectToAction("Index");
}
}
查看:
@if(TempData["SuccessMessage"] != null)
{
<div class="alert @TempData["SuccessMessage"].CssClassName">
<strong>@TempData["SuccessMessage"].Title</strong> @TempData["SuccessMessage"].Message
</div>
}
但我在CssClassName
中的某些对象Title
,Message
,TempData["SuccessMessage"]
上收到错误,我也不知道为什么。我知道有一个小技巧来解决这个问题。有人可以帮我弄这个吗?谢谢!
答案 0 :(得分:1)
您无法将匿名类型存储到TempData
中,但您可以创建一个类并将tempdata
转换为类似
public class ClsMsg
{
public string CssClassName { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
行动
TempData["SuccessMessage"] = new ClsMsg { CssClassName = "alert-success", Title = "Success!", Message = "You have successfully applied. Please wait for confirmation. Thank you!" };
并在视野中
@if (TempData["SuccessMessage"] != null)
{
ClsMsg msg = TempData["SuccessMessage"] as ClsMsg;
<div class="alert @msg.CssClassName">
<strong>@msg.Title</strong> @msg.Message
</div>
}