如何将View()返回到另一个动作而不会丢失@ Html.DropDownListFor()

时间:2015-06-05 15:07:05

标签: c# asp.net-mvc

在View中,我设计了一个@ Html.DropDownListFor()并将源放在public ActionResult Index(){...}中。它没有问题。

现在,我想通过其他操作引用Index()。像这样:

public ActionResult AnotherAction()
{
   // do something...
   return View("index");
}

当我运行AnotherAction()时,DropDownListFor()的所有数据都将丢失。

我的意思是:当我渲染到Index.cshtml时(在行return View("index");处),行动Index()中的代码将无法执行。因此数据源将丢失。

但是,如果我将该行更改为return RedirectToAction("index", "default");。没关系。

这是我的问题:在动作AnotherAction()中,我想将一些值存储到ViewBag中并在View中显示它。但是当我进行重定向时,ViewBag的所有值都将丢失。

我想使用return View("index"),而不是重新定位。

我的问题是:如何保留DropDownList的数据(在行动Index()中)和ViewBag的值(在行动AnotherAction()中)?

1 个答案:

答案 0 :(得分:0)

分开代码以构建您的DDL并从两个操作中调用它。

public ActionResult Index()
{
    //do index action related stuff
   BuildDataForDDL();
   return View("index");
}

public ActionResult AnotherAction(YourModel yourModel)
{
    //do another action related stuff
   BuildDataForDDL();
   ViewBag.Add(SelectedValue, yourModel.DropDownSelectedValue);
   return View("index");
}

private void BuildDataForDDL()
{
   // build ddl
   //ViewBag.Add(etc,etc);
}
  

当我运行AnotherAction()时,DropDownListFor()的所有数据都将丢失。

     

但是当我进行重定向时,ViewBag的所有值都将丢失。

不要将其视为重定向,也不要将数据丢失。

对YourController / AnotherAction的请求是路由引擎发送给该操作的另一个请求,这是对Index调用的完全独立的请求,它不共享这些请求之间ViewBag的状态。

由于这是一个新请求,因此ViewBag为空,因此您需要运行所需的所有代码,以便根据返回的结果构建所需的代码;在这种情况下,构建DDL数据并将其放入ViewBag。