重定向到不保留变量的不同控制器的操作

redirect to action of different controller not retaining variable

我正在从一个控制器重定向到另一个控制器,并在路由值中发送一个对象,但该对象返回为空:

class Person {
 string Name {get; set;}
}

FirstController {
 ActionResult something() {
  Person p = new Person() { Name = "name" };
  return redirectToAction("AddPerson", "Second", new { person = p });
 }
}

SecondController {
 ActionResult AddPerson(Person person) {
  //I'm hitting this action method but the "person" object is always null for some reason
  //add person
 }
}

是不是因为不允许传递物品?

我尝试将参数更改为字符串而不是 Person 对象,然后只发送 person.Name 然后它发送了......但是为什么?

您不能像使用内置实用程序那样通过查询字符串传递复杂对象。

您应该发送对该对象的引用(类似于 ID),您可以在另一端重新查找它。这仅在 Person 存储在某个地方(会话、数据库等)时有效。

除此之外,您必须单独发送对象的每个属性并重建它。您也可以查看类似这样的内容:How do I serialize an object into query-string format? 并可能构建您自己的序列化对象的实用程序。但是您仍然需要在您的接收方法上重建它,因为这不会自动完成。

发布的表单也可以映射到在操作参数中定义的模型,但这看起来不像您正在尝试做的那样。