.NET MVC : Calling RedirectToAction passing a model?

瘦欲@ 提交于 2019-12-17 10:52:33

问题


I got a view List.aspx that is bound to the class 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?

Thanks!


回答1:


I think you just need to call view like

return RedirectToAction("List", new {id});

with id you need to populate the Kindergarten.




回答2:


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.

[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)




回答3:


I'm not sure you want to call RedirectToAction because that will just cause k to be set again.

I think you want to call View and pass in the name of the view and your model.

return View("List", k);



回答4:


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 int as its parameter.

Think of RedirectToAction as a method call.



来源:https://stackoverflow.com/questions/2324044/net-mvc-calling-redirecttoaction-passing-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!