如何通过RedirectToAction传递类

时间:2012-02-21 09:45:31

标签: asp.net-mvc-3 redirecttoaction

我有以下代码:

    public ActionResult Index()
    {
        AdminPreRegUploadModel model = new AdminPreRegUploadModel()
        {
            SuccessCount = successAddedCount,
            FailureCount = failedAddedCount,
            AddedFailure = addedFailure,
            AddedSuccess = addedSuccess
        };
        return RedirectToAction("PreRegExceUpload", new { model = model });
    }

    public ActionResult PreRegExceUpload(AdminPreRegUploadModel model)
    {
        return View(model);
    }

但是当我在PreRegExcelUpload上断点时,模型为空。为什么呢?

3 个答案:

答案 0 :(得分:1)

我建议使用Session而不是在Evgeny Levin的回答中使用TempData对象。关于TempData,请参阅http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications

您也可以通过在return PreRegExceUpload(model);函数中调用return RedirectToAction(..)而不是Index来解决此问题。

答案 1 :(得分:1)

TempData只是Session的“智能”包装器,它在幕后仍然以相同的方式运行。

因为它只有4个字段,所以我会通过querystring传递它们。

总是尽量避免使用session / tempdata,在这种情况下肯定是这样。

你确定这是你的完整代码吗?因为它没有意义。

如果您对某些数据进行POST并将其保存到数据库(例如),通常会重定向到另一个传递唯一标识符的操作(通常在保存后生成),从数据库中取回并返回图。

这是更好的做法。

如果你更多地解释你的情景,并显示你使用的正确代码,我可以进一步帮助。

答案 2 :(得分:0)

使用session将模型传递给方法:

public ActionResult Index()
{
    AdminPreRegUploadModel model = new AdminPreRegUploadModel()
    {
        SuccessCount = successAddedCount,
        FailureCount = failedAddedCount,
        AddedFailure = addedFailure,
        AddedSuccess = addedSuccess
    };
    Session["someKey"] = model;
    return RedirectToAction("PreRegExceUpload");
}

public ActionResult PreRegExceUpload()
{
    var model = (AdminPreRegUploadModel) Session["someKey"];
    Session["someKey"] = null;
    return View(model);
}

方法RedirectToAction()不能将非基本类型作为参数,因为url参数是字符串。

相关问题