0

Thanks everyone's effort of helping me out, basically I'm facing a problem in controller below, just make it simple and easy:

Controller C{

       public list<model> a;
       //used in action A, if it's a searched list, then don't initialize;
       public bool searched = false;


       public ActionResult A(){
          if(searched){
             ViewBag.a = a;
          }else
          //initial the list
          a = db.model.where();
          .....
          return view()
       }

       //return a result list when people search by keywords
       public ActionResult B(string str){
          a = db.model.where(d=> d.id = str);
          search = true;
       }

    }

But, it turned out that the value of both a and researched never changed after B called

Did I miss some critical knowledge in .NET MVC?

Any related articles are very welcomed

Thanks

4

2 回答 2

1

Controller C将在每个请求上重新创建,因此即使在B调用后更新了值,下一个请求A也将需要创建控制器C,因此将重新实例化搜索。

您可能希望将局部变量设为静态。

于 2013-07-17T19:17:20.270 回答
1

您可能认为状态将在两个 Web 请求之间保留。但是当 Web 请求结束时,整个控制器被破坏并且设置的信息丢失,除非它存储在持久数据存储Session或数据库中。

如果我正确理解您的代码,如果您稍微重构代码,您可能可以通过一个操作实现搜索功能,并且您不需要持久存储数据。

于 2013-07-17T19:16:54.510 回答