如何将模型数据从一个控制器传递到另一个控制器

6

将模型数据从一个控制器传递到另一个控制器是可行的吗?

我想将模型数据传递给另一个控制器。

[HttpPost]
        public ActionResult Personal(StudentModel student)
        {                          
                return RedirectToAction("nextStep", new { model = student});          
        }

        public ActionResult nextStep(StudentModel model)
        {           
            return View(model);
        }

nextStep 控制器中,模型值为 null。 怎么办? 我需要在 nextStep 控制器中使用 StudentModel 数据。


1个回答

10

您正在使用RedirectToAction。它会发出GET请求。有两种方法可以在此传递您的模型。

1. TempData

您需要将模型持久化在TempData中,并进行RedirectToAction。但限制是它仅在即时请求中可用。在您的情况下,这不是问题。您可以使用TempData来实现。

public ActionResult Personal(StudentModel student)
{                          
       TempData["student"] = student;
       return RedirectToAction("nextStep", "ControllerName");          
}

public ActionResult nextStep()
{      
       StudentModel model= (StudentModel) TempData["student"];
       return View(model);
}

2. 通过查询字符串传递数据

由于请求是GET,我们可以将数据作为查询字符串传递,并使用模型属性名称。MVC模型绑定程序将解析查询字符串并将其转换为模型。

 return RedirectToAction("nextStep", new { Name = model.Name, Age=model.Age });

此外,请注意在查询字符串中传递敏感数据是不可取的

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接