从Base Controller返回后TempData为null

时间:2013-01-11 02:03:14

标签: c# asp.net-mvc asp.net-mvc-4 tempdata

TempData在Base方法中填充,但是一旦代码返回到派生控制器的方法,就会变为null。

派生控制器编辑操作(发布):

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
        );
    }

基本控制器编辑操作:

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);
    }

1 个答案:

答案 0 :(得分:0)

最后,我通过继承基本控制器而不是实例化新实例来解决这个问题。我创建的新实例必须与TempData混淆