asp.net-mvc .NET MVC:调用 RedirectToAction 传递模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2324044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.NET MVC : Calling RedirectToAction passing a model?
提问by Aximili
I got a view List.aspxthat is bound to the class Kindergarten
我有一个List.aspx绑定到类的视图Kindergarten
In the controller:
在控制器中:
public ActionResult List(int Id)
{
Kindergarten k = (from k1 in _kindergartensRepository.Kindergartens
where k1.Id == Id
select k1).First();
return View(k);
}
That works.
那个有效。
But this doesn't
但这不
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(...)
{
//...
Kindergarten k = ...
return RedirectToAction("List", k);
}
How should I redirect to the list view, passing k as the model?
我应该如何重定向到列表视图,将 k 作为模型传递?
Thanks!
谢谢!
采纳答案by Ashish
I think you just need to call view like
我认为你只需要像这样调用视图
return RedirectToAction("List", new {id});
return RedirectToAction("List", new {id});
with id you need to populate the Kindergarten.
使用 id 您需要填充幼儿园。
回答by Omar
I don't believe ModelBinding exists when using RedirectToAction. Your best options, however, is to use the TempData collection to store the object, and retrieve it in the following action.
我不相信使用 RedirectToAction 时存在 ModelBinding。但是,您最好的选择是使用 TempData 集合来存储对象,并在以下操作中检索它。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(...)
{
//...
Kindergarten k = ...
TempData["KG"] = k;
return RedirectToAction("List");
}
In your List Action
在您的列表操作中
public ActionResult List()
{
Kindergarten k = (Kindergarten)TempData["KG"];
// I assume you need to do some stuff here with the object,
// otherwise this action would be a waste as you can do this in the Add Action
return View(k);
}
Note: TempData collection only holds object for a single subsequent redirect. Once you make any redirect from Add, TempData["KG"] will be null (unless you repopulate it)
注意:TempData 集合仅保存单个后续重定向的对象。一旦您从 Add 进行任何重定向,TempData["KG"] 将为空(除非您重新填充它)
回答by Brandon
I'm not sure you want to call RedirectToActionbecause that will just cause k to be set again.
我不确定你想打电话,RedirectToAction因为那只会导致再次设置 k。
I think you want to call Viewand pass in the name of the view and your model.
我认为您想调用View并传入视图和模型的名称。
return View("List", k);
回答by Daniel T.
As Brandon said, you probably want to use return View("List", Id)instead, but the problem you're having is that you're passing k, your model, to a method that accepts an intas its parameter.
正如布兰登所说,您可能想return View("List", Id)改用,但您遇到的问题是您将k模型传递给接受 anint作为其参数的方法。
Think of RedirectToActionas a method call.
将其RedirectToAction视为方法调用。

