什么是ASP.NET MVC的通用控制器的目的 [英] What is the purpose of ASP.NET MVC Generic Controller

查看:98
本文介绍了什么是ASP.NET MVC的通用控制器的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在asp.net mvc的新手。我听到这个词 ASP.NET MVC的通用控制器,任何人都可以轻松地解释这是什么?我曾与前默认的控制器工作,但现在我想能够形象化样的目的ASP.NET MVC的通用控制器执行。这将是非常有益的,如果有人可以解释的情况时,开发人员必须考虑使用ASP.NET MVC的通用控制器。概念和如何实现它会大大AP preciated code。谢谢

I am newbie in asp.net mvc. I heard the word ASP.NET MVC generic controller, can anyone easily explain what it is? I have worked with the default controller before but now I want to able to visualize the kind of purpose ASP.NET MVC generic controller does. It will be very helpful if some one can explain the situations when a developer has to think about using ASP.NET MVC generic controller. Concepts and code about how to implement it will be greatly appreciated. Thanks

推荐答案

您通常会创建一个泛型类抽象掉的操作可以在一系列的类型执行,含有一个ID例如实体框架模型。在这种情况下,你可以将所有重复code到一个基类。

You usually create a generic class to abstract away operations you can perform on a range of types, for example Entity Framework models containing an ID. In that case you can move all duplicate code into a base class.

对于MVC控制器,通用的基本控制器可以是这样的:

For an MVC controller, a generic base controller may 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);
    }
}

和这样实现:

public class FooController : GenericController<Foo>
{

}

当有人要求 /美孚/详细信息/ 42 中,entitiy从拉 _repository 的<

现在code>设置&LT;富&GT;(),而无需编写任何东西,在 FooController的

Now when someone requests /Foo/Details/42, the entitiy is pulled from the _repository's Set<Foo>(), without having to write anything for that in the FooController.

这样你可以创建一个基本的CRUD控制器,可以让你轻松地创建,读取,更新扩展应用程序和删除操作的新车型。

This way you can create a basic "CRUD" controller that lets you easily extend your application with Create, Read, Update and Delete operations for new models.

这篇关于什么是ASP.NET MVC的通用控制器的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆