开发者

Why is TryUpdateModel on the Controller class in MVC protected?

Originally this was going to be a question asking ho开发者_如何学编程w to perform a task, but now it has turned into a question of best practice.

I am using MVC (still new to it) and I was trying to create a method that any controller can call that will run a common piece of functionality. Within the method, I needed to run the controller's TryUpdateModel method. This is where I was hitting a roadblock- I couldn't do this unless the method was IN the controller because TryUpdateModel is "inaccessible due to its protection level"- it is marked 'protected'. If I had to make this method private to each controller, it would defeat the whole purpose of having the method in the first place and I would be copy-pasting a lot of code.

So I was wondering, why is this method protected? Surely I must be missing something glaringly obvious. (And please do shed light)

What I ended up doing in creating my own controller class that inherits from the base controller class. This new class contains the method I needed to be common with all of my controllers. Now my controllers inherit from this new controller class I built that in turn inherits from the base controller class. It works well and seems to fit the model great.

My question is- for those that work with MVC regularly, is this model bad idea? Is it usually a bad idea to take such a central class and make your own and use it instead?


This is protected because these methods belong inside controller code. They are extensions of the controller meant to be used specifically in the controller. The fact they are protected means that by design the intention was there for this to happen in a controller. Take asp.net web forms for example, Page.IsPostback is meant to be called from within the page itself. The controller is generally where the model binding magic applies to, and hence TryUpdateModel belongs there as well. You may be trying to oversimplify a bit too much, but I do see why you would do this. Can you abstract one layer less? Use tryupdatemodel in your controller and any additional common code in another 'common' method.
Generally in mvc code in the controller stays fairly simply such that if !TryUpdateModel(model) then you simply return and let modelstate/validators do their magic. Its a simple method and generally works well. Are you saving 2/3 lines of common validation code by trying to implement this other method?

I'm not sure if (because of ModelState, etc) using another class that inherits from a controller, whose purpose isn't really a controller - will work in all cases - so beware with that. ModelState may not be passed around properly, etc.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜