代码之家  ›  专栏  ›  技术社区  ›  Aximili

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

  •  32
  • Aximili  · 技术社区  · 14 年前

    我看到了 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 回复  |  直到 14 年前
        1
  •  27
  •   Ashish    14 年前

    我想你只需要把视图称为

    返回RedirectToAction(“list”,new ID);

    有了身份证,你就得去幼儿园了。

        2
  •  55
  •   Omar    14 年前

    我不相信使用RedirectToAction时存在模型绑定。但是,最好的选择是使用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”]将为空(除非重新填充它)。

        3
  •  18
  •   Brandon    14 年前

    我不确定你想打电话给我 RedirectToAction 因为这只会导致K再次被设置。

    我想你想打电话给我 View 并以视图和模型的名称传递。

    return View("List", k);
    
        4
  •  1
  •   Daniel T.    14 年前

    正如布兰登所说,你可能想用 return View("List", Id) 相反,但你的问题是你路过 k ,您的模型,到接受 int 作为其参数。

    想想 RedirectToAction 作为方法调用。