asp.net-mvc-3 - 使用 redirectAction 和 prg 模式在 Action 之间发送数据

标签 asp.net-mvc-3

如何使用 redirectAction 在 Action 之间发送数据?

我正在使用 PRG 模式。我想做这样的事情

[HttpGet]
    [ActionName("Success")]
    public ActionResult Success(PersonalDataViewModel model)
    {
        //model ko
        if (model == null)
            return RedirectToAction("Index", "Account");

        //model OK
        return View(model);
    }

    [HttpPost]
    [ExportModelStateToTempData]
    [ActionName("Success")]
    public ActionResult SuccessProcess(PersonalDataViewModel model)
    {

        if (!ModelState.IsValid)
        {
            ModelState.AddModelError("", "Error");
            return RedirectToAction("Index", "Account");
        }

        //model OK
        return RedirectToAction("Success", new PersonalDataViewModel() { BadgeData = this.GetBadgeData });
    }

最佳答案

重定向时,您只能传递查询字符串值。不是整个复杂对象:

return RedirectToAction("Success", new {
    prop1 = model.Prop1,
    prop2 = model.Prop2,
    ...
});

这仅适用于标量值。因此,您需要确保在查询字符串中包含您需要的每个属性,否则它将在重定向中丢失。

另一种可能性是将您的模型保留在服务器上的某处(例如数据库或其他东西),并且在重定向时仅传递允许检索模型的 id:
int id = StoreModel(model);
return RedirectToAction("Success", new { id = id });

并在 Success 操作中检索模型:
public ActionResult Success(int id)
{
    var model = GetModel(id);
    ...
}

另一种可能性是使用 TempData 虽然我个人不推荐它:
TempData["model"] = model;
return RedirectToAction("Success");

并在 Success 操作中从 TempData 获取它:
var model = TempData["model"] as PersonalDataViewModel;

关于asp.net-mvc-3 - 使用 redirectAction 和 prg 模式在 Action 之间发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10752160/

相关文章:

asp.net - 如何使用 MVC 3 启用/使用跨源资源共享?

c# - 如何使 Fluent API 配置与 MVC 客户端验证一起使用?

c# - 每个实体的 MVC3 Controller 还是每个实体组的 Controller ?

c# - MVC3 字典未绑定(bind)到模型

jQuery 按钮导航到具有路由值的操作 Controller ?

asp.net - ASP.NET MVC 操作中的返回类型

javascript - CheckBoxFor 在 ASP.NET MVC 的 javascript 函数中返回以前的值

jquery - 为什么jquery函数无法对具有相同ID的两个图像执行

javascript - 从 javascript 调用操作方法时 Asp、Net MVC 应用程序的安全问题

c# - 如果 URL 包含片段,为什么 Url.IsLocalUrl 会返回 false?