当我序列化视图模型时,如何在控制器中“新建”视图模型?

时间:2013-03-06 23:47:52

标签: asp.net-mvc-3 asp.net-mvc-4

我在控制器中使用以下序列化

private MyViewModel myData;
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var serialized = Request.Form["myData"];
    if (serialized != null) //Form was posted containing serialized data
    {
    myData= (MyViewModel)new MvcSerializer().Deserialize
        (serialized, SerializationMode.Signed);
        TryUpdateModel(myData);
    }
    else
        myData= (MyViewModel)TempData["myData"] ?? new MyViewModel();
    TempData.Keep();
}
protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
    if (filterContext.Result is RedirectToRouteResult)
        TempData["myData"] = myData;
}

然后在我的控制器中的特定Action中,我会使用它来获得向导类型的功能:

public ActionResult Step5(string backButton, string nextButton)
{
    if (backButton != null)
        return RedirectToAction("Step4");
    else if ((nextButton != null) && ModelState.IsValid)
        return RedirectToAction("Confirm");
    else
        return View(myData);
}

我的问题是我现在遇到的情况是我必须在控制器的Action中执行类似的操作:

var model = new MyViewModel
{
    Notifications = new[]
    {
        NotificationDeliveryType.Email,
        NotificationDeliveryType.InSystem | NotificationDeliveryType.Text
    }
};
return View(model);

但我显然做不到,因为我已经开始做return View(myData);

有任何想法/解决方法吗?

提前致谢。

0 个答案:

没有答案