MVC C# - 最简单的可能实现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1107720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:25:00  来源:igfitidea点击:

MVC C# - Simplest Possible Implementation

c#asp.net-mvcdesign-patterns

提问by Dave Mateer

My first try of MVC. Am trying to implement a simpleexample. Inspiration from here. Have I got this pattern (yet!)?

我第一次尝试 MVC。我正在尝试实现一个简单的示例。灵感来自这里。我有这个模式(还!)?

  1. View: "Hey, controller, the user just told me he wants the first person"

  2. Controller: "Hmm, having checked his credentials, he is allowed to do that... Hey, model, I want you to get me the first person"

  3. Model: "First person... got it. Back to you, Controller."

  4. Controller: "Here, I'll collect the new set of data. Back to you, view."

  5. View: "Cool, I'll show the first person to the user now."

  1. 视图:“嘿,控制器,用户刚刚告诉我他想要第一人称”

  2. 管制员:“嗯,在检查了他的凭据后,他被允许这样做......嘿,模型,我希望你让我成为第一人”

  3. 模型:“第一人称......明白了。回到你身边,控制器。”

  4. 管制员:“来,我会收集新的数据集。返回给你,查看。”

  5. 视图:“很酷,我现在将第一个人显示给用户。”

View:

看法:

namespace WinFormMVC
{
    public partial class Form1 : Form
    {
        controller cont = new controller();

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = cont.checkPermissionsAndGetFirstPerson();
        }
    }
}

Controller:

控制器:

public class controller
    {
        public string checkPermissionsAndGetFirstPerson()
        {
            string returnValue = "";
            if (checkPermissions())
            {
                model m = new model();
                returnValue =  m.getFirstPerson();
            }

            return returnValue;

        }

        public bool checkPermissions()
        {
            return true;
        }
    }

Model:

模型:

public class model
    {
        public string getFirstPerson()
        {
            return "Bill Smith";
        }
    }

采纳答案by Jimmy Chandra

Hmm... I am not sure if I'd call this MVC... As with ASP.NET WebForm, this form is more like an MVP pattern.

嗯...我不确定我是否将其称为 MVC...与 ASP.NET WebForm 一样,此表单更像是一种 MVP 模式。

As per my understanding, in MVC, controller is the one responsible for managing all resources and flow of the code. In your example, you basically creating a Windows Form first (the view) and then attach a controller to it which is more of a MVP sort of things.

根据我的理解,在 MVC 中,控制器负责管理代码的所有资源和流。在您的示例中,您基本上首先创建了一个 Windows 窗体(视图),然后将一个控制器附加到它上面,这更像是一种 MVP 类型的东西。

In a classical MVC pattern, the Model, once instantiated, will be linked to the View and when the model changes, the view will get notified (possibly through Observer / PubSub pattern).

在经典的 MVC 模式中,模型一旦实例化,将链接到视图,当模型更改时,视图将收到通知(可能通过观察者/发布订阅模式)。

Button click, etc. from the View will be routed to the controller which will coordinate those sort of stuffs.

来自视图的按钮点击等将被路由到控制器,控制器将协调这些类型的东西。

see: this.

见:这个

回答by CoderDennis

Your checkPermissionsAndGetFirstPersonmethod is probably doing too much. Authorization and fetching data should probably be separate operations.

你的checkPermissionsAndGetFirstPerson方法可能做得太多了。授权和获取数据应该是分开的操作。

Also, if your Form1class is your view, it probably shouldn't be constructing the controller. That seems backwards.

此外,如果您的Form1类是您的视图,则它可能不应该构建控制器。这似乎倒退了。

Most information you'll find on MVC in .NET will be for ASP.NET MVC web applications. You might want to check out the WinFormsMVC project on CodePlex to see how someone else has tackled this problem.

您将在 .NET 中找到的关于 MVC 的大多数信息都适用于 ASP.NET MVC Web 应用程序。您可能想查看 CodePlex 上的 WinFormsMVC 项目,看看其他人是如何解决这个问题的。

http://winformsmvc.codeplex.com/

http://winformsmvc.codeplex.com/

Here's another WinForms MVC implementation on CodePlex. Looks like it's got a bit more documentation.

这是 CodePlex 上的另一个 WinForms MVC 实现。看起来它有更多的文档。

http://koosserymvcwin.codeplex.com/

http://koosserymvcwin.codeplex.com/

回答by James

To adopt the MVC pattern you want to implement the following:

要采用 MVC 模式,您需要实现以下内容:

  • The view hooks up to the Model and listens for changes.
  • The controller hooks up to the view and handles specific events i.e. button presses etc
  • The model processes requests made by the controller and notifies the view.
  • 视图连接到模型并侦听更改。
  • 控制器连接到视图并处理特定事件,即按钮按下等
  • 模型处理控制器发出的请求并通知视图。

I agree with Jimmy you would want to integrate something like the Observerpattern to this type of system so its possible for the Model to inform the View when it changes so the View can then update itself accordingly.

我同意 Jimmy的观点,您希望将观察者模式之类的东西集成到这种类型的系统中,这样模型就有可能在视图发生变化时通知视图,以便视图可以相应地更新自己。

The difference with MVP is it introduces a Presenter class which monitors the Model on behalf of the View, in other words the View doesn't know about the Model, it only knows about its Presenter. The Presenter responds to changes in the Model and updates the View accordingly.

与MVP的不同之处在于它引入了一个Presenter类,它代表View监视Model,换句话说View不知道Model,它只知道它的Presenter。Presenter 响应模型中的更改并相应地更新视图。

回答by synhershko

You might find this tutorial very helpful: http://nerddinnerbook.s3.amazonaws.com/Intro.htm. Written by Scott Guthrie, it explains the MVC workflow very well. Part 4 should have the basics you're looking for.

您可能会发现本教程非常有帮助:http: //nerddinnerbook.s3.amazonaws.com/Intro.htm。由 Scott Guthrie 撰写,它很好地解释了 MVC 工作流程。第 4 部分应该包含您正在寻找的基础知识。

回答by Keith

I would describe MVC more like this:

我会更像这样描述MVC:

  1. Request (MVC url routing, some event passed from previous UI etc)

  2. Controller - check credentials, get data, return Model

  3. Model - represents the data passed back from the Controller

  4. View - render the Model returned by the Controller. Depending on the Model may display UI to initialise new Controller actions. May also pass Model back to next Controller action.

  1. 请求(MVC url 路由,从以前的 UI 传递的一些事件等)

  2. 控制器 - 检查凭据,获取数据,返回模型

  3. Model - 表示从 Controller 传回的数据

  4. 视图 - 呈现控制器返回的模型。根据模型可能会显示 UI 以初始化新的控制器操作。也可以将模型传递回下一个控制器操作。

I think it can be a little confused because in many Model implementations (such as Linq) they provide data definition and access, but it's still the Controller that knows where to start (even if it's the Model that knows how to save its own changes).

我认为这可能有点混乱,因为在许多 Model 实现(例如 Linq)中,它们提供数据定义和访问,但仍然是 Controller 知道从哪里开始(即使是 Model 知道如何保存自己的更改) .

So, your code should be something like:

所以,你的代码应该是这样的:

//Controller:
public class PersonController
{
    public PersonAction Detail(int personId)
    {
        Person returnValue;
        //get person from DB and populate returnValue
        return new PersonAction( returnValue );
    }
}

//Model:
public class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

//View:
public partial class PersonDetailView : MVCForm<Person>
{
    public Form1( Person model ):base(model) {
        textBox1.Text = model.FirstName + " " + model.LastName;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Text = model.FirstName + " " + model.LastName;
    }
}

What this example is missing is the framework that makes this all possible - there are two significant parts to that:

这个例子缺少的是使这一切成为可能的框架 - 有两个重要部分:

  1. Something that takes/parses parameters and based on that calls a controller's action method. For instance in Asp.net MVC this is the routing handlers - the call above would be the request url: ~/Person/Detail/personId

  2. Something that takes the result from the action (PersonActionin the example above) and finds the correct view to display. In this example it would open a PersonDetailViewform and pass the Personmodel to it.

  1. 接受/解析参数并基于它调用控制器的操作方法的东西。例如,在 Asp.net MVC 中,这是路由处理程序 - 上面的调用将是请求 url: ~/Person/Detail/personId

  2. 从操作中获取结果(PersonAction在上面的示例中)并找到要显示的正确视图的东西。在这个例子中,它将打开一个PersonDetailView表单并将Person模型传递给它。

There are lots of example frameworks for an MVC implementation for WinForms - one of them may be a good starting point.

WinForms 的 MVC 实现有很多示例框架 - 其中一个可能是一个很好的起点。

回答by Hyman Ryan

I think there are a few corrections to be made to your narrative. Strinctly speaking the view does not contact the controller, the user contacts the controller directly. In a web app it looks like this.

我认为对你的叙述有一些更正。严格来说视图不接触控制器,用户直接接触控制器。在网络应用程序中,它看起来像这样。

  1. User: Hey web app, can I have the resource at /people/1

  2. Routing engine: That means you person controller. get the first user.

  3. User controller: Model, I need you to get me user record for the authenticated user, and the person record for the first person.

  4. User Controller: Right. I know the authenticated user is an admin, and person one does exist. So return the Admin view for person to the user.

  5. Rendering engine: Build up the html from the view (template) and person object (data)

  1. 用户:嘿 Web 应用程序,我可以在 /people/1 获得资源吗

  2. 路由引擎:这意味着您是个人控制器。获得第一个用户。

  3. 用户控制器:模型,我需要你为我获取认证用户的用户记录,以及第一人的个人记录。

  4. 用户控制器:对。我知道经过身份验证的用户是管理员,并且确实存在一个人。因此,将人员的 Admin 视图返回给用户。

  5. 渲染引擎:从视图(模板)和人物对象(数据)构建 html

This is difficult to do in webforms. I guess the best way is to have a page for each controller, and have that page dynamiclly choose and display a user control. One for each view. It is important in MVC that the view is dumb. All requests are handled directly by controllers, which then select which view to use.

这在网络表单中很难做到。我想最好的方法是为每个控制器设置一个页面,并让该页面动态选择和显示用户控件。每个视图一个。在 MVC 中,视图是愚蠢的,这一点很重要。所有请求都由控制器直接处理,然后控制器选择要使用的视图。