开发者

What conforming standards is this code violating?

开发者 https://www.devze.com 2023-03-23 12:01 出处:网络
What is wrong with having a private ViewModel object, so that all my controller actions have access to it?

What is wrong with having a private ViewModel object, so that all my controller actions have access to it?

  • I'm using EF4,MVC3,DBContext, DB开发者_开发问答sets.

    public class MyController {
    
    private MyViewModel _myViewModel;
    
    public ActionResult Index(MyViewModel myViewModel){ <-- There is a model Binder making this work
    
    _myViewModel = myViewModel;
    
    return _myViewModel;
    }
    
    }
    


Because everytime you call a controller action you get a different instance of the controller. So anything that you might have stored in instance fields of this controller from a previous action would be lost on subsequent actions. That's the reason why in ASP.NET MVC you have notions such as Session, Application State, TempData, Cookies, Cache, ... you name it.


For one thing, by making the ViewModel a member of your controller, you really limit what you can do in a multi-threaded environment. If more than 1 of your Actions is invoked on the same controller, you may end up with a race condition to determine which of the passed-in view models is used for each view.

Edit: You get a different instance of the controller each time, so this will not happen. However, it is still something to keep in mind for other classes that use private members

0

精彩评论

暂无评论...
验证码 换一张
取 消