我正试图将视图模型和一些其他数据从一个控制器动作方法传递到同一控制器内的另一个动作方法。参数参数对需要处理各种视图模型。为此,我将视图模型对象和其他数据存储在对象中。
public class infViewModel
{
//Fields...
}
public class infElement
{
public Guid ID { get; set; }
public object ViewModel { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult actionOne(infViewModel pCurrentViewModel)
{
infViewModel _CurrentViewModel = new infViewModel();
_CurrentViewModel = pCurrentViewModel;
infElement _Element = new infElement();
_Element.ViewModel = _CurrentViewModel;
return RedirectToAction(“actionTwo”, _Element);
}
public ActionResult actionTwo(infElement pElement)
{
}
我可以传递不同类型的数据,例如string
和Guid
,但无法传递包含视图模型的对象。
我观察到自变量和参数之间的数据丢失:参数对象_Element
的QuickWatch
显示了完整的预期数据,包括_Element.ViewModel
对象以及ViewModel的字段和字段各自的内容。
另一方面,参数对象pElement
的QuickWatch
表示pElement.ViewModel
对象变成了纯字符串。该字符串是名称空间、类等的串联。同时,其他数据(如pElement.ID
)看起来完好无损。
我制作了infElement
通用版:
public class infElement<T>
{
public Guid ID { get; set; }
public T ViewModel { get; set; }
}
但结果基本相同,只是现在pElement.ViewModel
是null
。
我应该如何在行动结果之间传递视图模型?
这是TempData
适用的地方:
public ActionResult actionOne(infViewModel pCurrentViewModel)
{
infViewModel _CurrentViewModel = new infViewModel();
_CurrentViewModel = pCurrentViewModel;
infElement _Element = new infElement();
_Element.ViewModel = _CurrentViewModel;
TempData["_Element"] = _Element;
return RedirectToAction("actionTwo");
}
public ActionResult actionTwo()
{
var _Element = TempData["_Element"] as infElement;
// ...
}