Best way to do global viewdata in an area of my ASP.NET MVC site?

前端 未结 2 1680
南笙
南笙 2021-02-09 01:00

I have an several controllers where I want every ActionResult to return the same viewdata. In this case, I know I will always need basic product and employee information.

<
2条回答
  •  别那么骄傲
    2021-02-09 01:49

    I thought of having my controller inherit a class that pretty much does the same thing you see here, but I didn't see any great advantages to that.

    This is the way to go, in my opinion. You'd create a base Controller class that would provide this functionality. If you are familiar with the ASP.NET WebForms model then this is similar to creating a custom base Page class.

    As to the advantages of putting it in a base class, the main advantages are readability, maintainability and reusability. If you copy and paste the above method into each controller that needs it, you are going to have a more difficult time if, down the road, you need to add new information to the ViewData collection.

    In short, anytime you catch yourself copying and pasting code among classes or views in your application you should stop and think about how to put such logic in a single place. For more, read up on DRY - Don't Repeat Yourself.

提交回复
热议问题