具有模型和列表属性的RedirectToAction [英] RedirectToAction with model and List properties
问题描述
我有2个视图,模型为Account.从视图1开始,我正在使用RedirectToAction转到视图2,并如下所示发送模型对象:
I have a 2 views with model as Account. From view one, I am using RedirectToAction to go to view two and sending the model object as below:
[HttpPost]
public ActionResult Login(Account account)
{
//Some code here
return RedirectToAction("Index", "AccountDetail", account);
}
AccountDetail控制器如下所示:
AccountDetail controller looks like this:
public ActionResult Index(Account account)
{
return View("ViewNameHere", account);
}
模型对象包含这样的属性:
The model object contains a property like this:
public class Account
{
// Some code here
public List<Details> Details{
get;
set;
}
在第一个控制器中,调用RedirectToAction
之前,详细信息"中有一项.但是,在第二个控制器的Index方法中,什么也没有.
In the first controller, before making call to RedirectToAction
there is one item in Details. However, in the Index method of second controller, there is nothing.
有人可以帮助指出这里的缺陷吗?由于我是MVC的初学者,所以似乎无法弄清楚.
Can someone help pointing out the flaw here? Since I am beginner with MVC, cannot seem to figure it out.
推荐答案
您不应将复杂的对象传递给GET方法.除了会创建丑陋的URL之外,您还可以轻松超过查询字符串的限制并引发异常.
You should not pass a complex object to a GET method. Apart from the ugly URL it would create, you could easily exceed the query string limit and throw an exception.
无论如何,您都不能使用RedirectToAction()
将集合(或包含集合的复杂对象)传递给GET方法.在内部,该方法使用反射通过调用模型每个属性的.ToString()
方法来生成查询字符串,对于您的collection属性,该方法类似于../AccountDetail/Index?Details=System.Collections.Generic.List<Details>
.
In any case you cannot pass a collection (or a complex object containing a collection) to a GET method using RedirectToAction()
. Internally the method uses reflection to generate the query string by calling the .ToString()
method of each property of the model, which in the case of your collection property will be something like ../AccountDetail/Index?Details=System.Collections.Generic.List<Details>
.
调用Index()
方法时,将初始化Account
的新实例,并尝试将其属性Details
的值设置为字符串System.Collections.Generic.List<Details>
,该字符串失败,结果是属性Details
是null
.
When the Index()
method is called, a new instance of Account
is initialized and the value of its property Details
is attempted to be set to the string System.Collections.Generic.List<Details>
which fails and the result is that property Details
is null
.
选项包括传递标识符并从存储库或Session
或TempData
Options include passing an identifier and get the collection from the repository or Session
or TempData
这篇关于具有模型和列表属性的RedirectToAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!