从基本控制器返回后,TempData为空
本文关键字:TempData 为空 返回 控制器 | 更新日期: 2023-09-27 17:51:14
TempData在Base方法中填充,但在代码返回到派生控制器的方法时变为null。
派生控制器编辑动作(Post):
public class ManageItemsController : BaseController
{
private BaseControllerSingle<Item, ItemViewModel> GetBaseControllerSingle()
{
return new BaseControllerSingle<Item, ItemViewModel>(_itemRepository, AreaName, ControllerName);
}
...
// POST: /InventoryMgmt/ManageItems/Edit/5
[HttpPost]
public ActionResult Edit(ItemViewModel ItemViewModel)
{
ItemViewModel = _manageItemsAppServ.SaveOrUpdate(ItemViewModel, CurrentCompanyId);
return GetBaseControllerSingle().EditPost(
ItemViewModel,
x => x.Id == ItemViewModel.Item.Id && x.CompanyId == CurrentCompanyId
);
}
Base Controller Edit Action:
public class BaseControllerSingle<TRepository, TViewModelSingle> : BaseController
where TRepository : class, IEntity, IAuditStamps, new()
where TViewModelSingle : class, IEntity, IViewModelSingle<TRepository, TViewModelSingle>, new()
{
...
public virtual ActionResult EditPost(
TViewModelSingle viewModel,
Expression<Func<TRepository, bool>> predicate = null
)
{
if (ModelState.IsValid)
{
BaseAppServSingle<TRepository, TViewModelSingle> baseAppServSingle =
new BaseAppServSingle<TRepository, TViewModelSingle>(_repository);
ActionConfirmation<int> result = baseAppServSingle.SaveOrUpdate(
viewModel,
CurrentUserId,
predicate
);
TempData["message"] = result.Message;
if (result.WasSuccessful)
{
return RedirectToAction("Edit", new { id = result.Value });
}
}
TempData["message"] = "There is invalid data on the form.";
return View(viewModel);
}
最后,我通过从基本控制器继承而不是实例化一个新实例来解决这个问题。我创建的新实例一定是与TempData