.NET MVC:调用RedirectToAction传递模型?

时间:2010-02-24 06:09:39

标签: asp.net-mvc asp.net-mvc-2

我有一个与List.aspx

类绑定的视图Kindergarten

在控制器中:

public ActionResult List(int Id)
{
  Kindergarten k = (from k1 in _kindergartensRepository.Kindergartens
                    where k1.Id == Id
                    select k1).First();

  return View(k);
}

有效。

但这不是

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(...)
{
  //...
  Kindergarten k = ...
  return RedirectToAction("List", k);
}

我应该如何重定向到列表视图,将k作为模型传递?

谢谢!

4 个答案:

答案 0 :(得分:56)

使用RedirectToAction时,我不相信ModelBinding存在。但是,最好的选择是使用TempData集合来存储对象,并在以下操作中检索它。

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(...)
{
  //...
  Kindergarten k = ...
  TempData["KG"] = k;
  return RedirectToAction("List");
}

在列表操作

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);
}

注意:TempData集合仅保存单个后续重定向的对象。一旦你从Add进行任何重定向,TempData [“KG”]将为null(除非你重新填充它)

答案 1 :(得分:27)

我认为你只需要调用像

这样的视图
  

返回RedirectToAction(“List”,新的   {ID});

你需要填写幼儿园。

答案 2 :(得分:18)

我不确定您是否要拨打RedirectToAction,因为这会导致k再次被设置。

我想你想调用View并传递视图名称和模型。

return View("List", k);

答案 3 :(得分:1)

正如Brandon所说,你可能想要使用return View("List", Id)代替,但你遇到的问题是你将k(你的模型)传递给接受{{1}的方法作为参数。

int视为方法调用。