本文介绍了RedirectToAction(..)具有复杂深刻的对象失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个控制器动作传递到另一个对象。我正在绕过物体看起来或多或少是这样的:

I'm trying to pass an object from one controller action to another. The object that I'm passing around looks more or less like this:

public class Person
{
   public string Name { get; set; }
   public List<PhoneNumber> PhoneNumbers {get; set; }
   public List<Address> Addresses { get; set; }
}

我的控制器看起来是这样的:

My Controller looks like this:

public class DialogController : Controller
{
    public ActionResult Index()
    {
        // Complex object structure created
        Person person = new Person();
        person.PhoneNumbers = new List();
        person.PhoneNumbers.Add("12341324");

        return RedirectToAction("Result", "Dialog", person);

    }

    public ActionResult Result(Person person)
    {
        string number = person.PhoneNumbers[0].ToString();
        return View();
    }
}

结果的方法失败,一个空指针异常,因为PHONENUMBERS列表与RedirectToAction()方法调用结果动作之后突然空。

The result method fails with a null pointer exception since the PhoneNumbers list is suddenly null after invoking the Result action with the RedirectToAction() method.

有没有人见过这种类型的行为?

Has anyone seen this type of behavior before?

干杯,

彼得

推荐答案

我同意@Dennis - 除非你想要的网址改变,那么你就必须想别的东西。其原因在于RedirectToAction不序列的数据时,它简单地在路由中的值的属性迭代对象构造查询字符串的键是属性名称和值的串重新属性值的presentation。如果你想有网址的变化,然后用TempData的可能是做最简单的方法,虽然你也可以在物品存储在数据库中,通过ID到结果的方法,并从那里重建它。

I agree with @Dennis -- unless you want the Url to change, then you'll have to think of something else. The reason is that RedirectToAction doesn't serialize the data, it simply iterates over the properties in the route values object constructing a query string with the keys being the property names and the values the string representation of the property values. If you want to have the Url change, then using TempData is probably the easiest way to do this, although you could also store the item in the database, pass the id to the Result method, and reconstitute it from there.

这篇关于RedirectToAction(..)具有复杂深刻的对象失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 23:17