What is the purpose of ASP.NET MVC Generic Controller

I am new to asp.net mvc. I heard the word ASP.NET MVC generic controller , can anyone easily explain what it is? I used to work with the default controller, but now I want to visualize the kind of target that the common ASP.NET MVC controller executes. It will be very useful if someone can explain situations when a developer has to think about using a universal ASP.NET MVC controller. Concepts and code on how to implement it will be greatly appreciated. Thanks

-3
source share
1 answer

Usually you create a general class for abstract operations that you can perform in different types, for example, Entity Framework models that contain an identifier. In this case, you can move all the duplicated code to the base class.

For an MVC, a common base controller might look like this:

 public abstract class GenericController<T> where T : class { public virtual ActionResult Details(int id) { var model = _repository.Set<T>().Find(id); return View(model); } } 

And the implementation is this:

 public class FooController : GenericController<Foo> { } 

Now, when someone asks for /Foo/Details/42 , entitiy is extracted from _repository Set<Foo>() , without having to write anything for this in FooController .

In this way, you can create a basic “CRUD” controller that allows you to easily expand your application using the Create, Read, Update, and Delete operations for new models.

+8
source

Source: https://habr.com/ru/post/958166/


All Articles