asp.net-mvc 除了我之外,有没有人不了解 ASP.NET MVC?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/390693/
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-09-07 23:14:29  来源:igfitidea点击:

Does anyone beside me just NOT get ASP.NET MVC?

asp.net-mvc

提问by FlySwat

I've been fiddling with ASP.NET MVC since the CTP, and I like a lot of things they did, but there are things I just don't get.

自 CTP 以来,我一直在摆弄 ASP.NET MVC,我喜欢他们所做的很多事情,但有些事情我就是不明白。

For example, I downloaded beta1, and I'm putting together a little personal site/resume/blog with it. Here is a snippet from the ViewSinglePost view:

例如,我下载了 beta1,我正在用它整理一个小的个人网站/简历/博客。这是 ViewSinglePost 视图中的一个片段:

 <%
        // Display the "Next and Previous" links
        if (ViewData.Model.PreviousPost != null || ViewData.Model.NextPost != null)
        {
            %> <div> <%

            if (ViewData.Model.PreviousPost != null)
            {
                %> <span style="float: left;"> <%
                    Response.Write(Html.ActionLink("<< " + ViewData.Model.PreviousPost.Subject, "view", new { id = ViewData.Model.PreviousPost.Id }));
                %> </span> <%
            }

            if (ViewData.Model.NextPost != null)
            {
                %> <span style="float: right;"> <%
                    Response.Write(Html.ActionLink(ViewData.Model.NextPost.Subject + " >>", "view", new { id = ViewData.Model.NextPost.Id }));
                %> </span> <%
            }
            %>
                   <div style="clear: both;" />
               </div> <%
        }
    %>

Disgusting! (Also note that the HTML there is temporary placeholder HTML, I'll make an actual design once the functionality is working).

恶心!(另请注意,HTML 是临时占位符 HTML,一旦功能正常,我将进行实际设计)

Am I doing something wrong? Because I spent many dark days in classic ASP, and this tag soup reminds me strongly of it.

难道我做错了什么?因为我在经典 ASP 中度过了许多黑暗的日子,而这个标签汤让我强烈地想起了它。

Everyone preaches how you can do cleaner HTML. Guess, what? 1% of all people look at the outputted HTML. To me, I don't care if Webforms messes up my indentation in the rendered HTML, as long as I have code that is easy to maintain...This is not!

每个人都在宣扬如何做更干净的 HTML。你猜怎么着?1% 的人会查看输出的 HTML。对我来说,我不在乎 Webforms 是否在呈现的 HTML 中弄乱了我的缩进,只要我有易于维护的代码......这不是!

So, convert me, a die hard webforms guy, why I should give up my nicely formed ASPX pages for this?

所以,转换我,一个顽固的 webforms 家伙,为什么我应该为此放弃我的漂亮的 ASPX 页面?

Edit:Bolded the "temp Html/css" line so people would stfu about it.

编辑:将“temp Html/css”行加粗,这样人们就会对此感到厌烦。

回答by Mark Brittingham

Compared to Web Forms, MVC is simultaneously a lower-level approach to HTML generation with greater control over the page output anda higher-level, more architecturally-driven approach. Let me capture Web Forms and MVC and show why I think that the comparison favors Web Forms in many situations - as long as you don't fall into some classic Web Forms traps.

与 Web 表单相比,MVC 同时是一种较低级别的 HTML 生成方法,可以更好地控制页面输出,也是一种更高级、更受架构驱动的方法。让我抓住 Web Forms 和 MVC 并说明为什么我认为在许多情况下这种比较有利于 Web Forms - 只要您不落入一些经典的 Web Forms 陷阱。

Web Forms

网页表格

In the Web Forms model, your pages correspond directly to the page request from the browser. Thus, if you are directing a user to a list of Books, you'll likely have a page somewhere called "Booklist.aspx" to which you'll direct him. In that page, you'll have to provide everything needed to show that list. This includes code for pulling data, applying any business logic, and displaying the results. If there is any architectural or routing logic affecting the page, you'll have to code the architectural logic on the page as well. GoodWeb Forms development usually involves the development of a set of supporting classes in a separate (unit-testable) DLL. These class(es) will handle business logic, data access and architectural/routing decisions.

在 Web 表单模型中,您的页面直接对应于来自浏览器的页面请求。因此,如果您将用户引导至书籍列表,您可能会在某处有一个名为“Booklist.aspx”的页面,您可以将其引导至该页面。在该页面中,您必须提供显示该列表所需的一切。这包括用于提取数据、应用任何业务逻辑和显示结果的代码。如果有任何影响页面的架构或路由逻辑,您还必须在页面上对架构逻辑进行编码。 好的Web 窗体开发通常涉及在单独的(可单元测试的)DLL 中开发一组支持类。这些类将处理业务逻辑、数据访问和架构/路由决策。

MVC

MVC

MVC takes a more "architectural" view of web application development: offering a standardized scaffold upon which to build. It also provides tools for automatically generating model, view and controller classes within the established architecture. For example, in both Ruby on Rails (just "Rails" from here on out) and ASP.NET MVC you'll always start out with a directory structure that reflects their overall model of web application architecture. To add a view, model and controller, you'll use a command like Rails's "Rails script/generate scaffold {modelname}" (ASP.NET MVC offers similar commands in the IDE). In the resulting controller class, there will be methods ("Actions") for Index (show list), Show, New and Edit and Destroy (at least in Rails, MVC is similar). By default, these "Get" Actions just bundle up the Model and route to a corresponding view/html file in the "View/{modelname}" directory (note that there are also Create, Update and Destroy actions that handle a "Post" and route back to Index or Show).

MVC 对 Web 应用程序开发采取更“架构”的观点:提供一个标准化的脚手架来构建。它还提供了在已建立的体系结构中自动生成模型、视图和控制器类的工具。例如,在 Ruby on Rails(从现在开始仅称为“Rails”)和 ASP.NET MVC 中,您总是从反映 Web 应用程序架构整体模型的目录结构开始。要添加视图、模型和控制器,您将使用类似 Rails 的“Rails 脚本/生成脚手架 {modelname}”的命令(ASP.NET MVC 在 IDE 中提供了类似的命令)。在生成的控制器类中,会有 Index(显示列表)、Show、New 和 Edit 和 Destroy 的方法(“Actions”)(至少在 Rails 中,MVC 是类似的)。默认情况下,这些“

The layout of directories and files is significant in MVC. For example, in ASP.NET MVC, the Indexmethod for a "Book" object will likely just have one line: "Return View();" Through the magic of MVC, this will send the Book model to the "/View/Books/Index.aspx" page where you'll find code to display Books. Rails's approach is similar although the logic is a bit more explicit and less "magic." A Viewpage in an MVC app is usually simpler than a Web Forms page because they don't have to worry as much about routing, business logic or data handling.

目录和文件的布局在 MVC 中很重要。例如,在 ASP.NET MVC 中,“Book”对象的Index方法可能只有一行:“Return View();” 通过 MVC 的魔力,这会将 Book 模型发送到“/View/Books/Index.aspx”页面,您将在其中找到显示 Books 的代码。Rails 的方法与此类似,但逻辑更明确且不那么“神奇”。一个视图中的MVC应用程序页面通常比Web窗体页面简单,因为他们不必担心,因为很多关于路由,业务逻辑和数据处理。

Comparison

比较

The advantages of MVC revolve around a clean separation of concerns and a cleaner, more HTML/CSS/AJAX/Javascript-centric model for producing your output. This enhances testability, provides a more standardized design and opens the door to a more "Web 2.0" type of web site.

MVC 的优势围绕着清晰的关注点分离和更清晰、更以 HTML/CSS/AJAX/Javascript 为中心的模型来生成您的输出。这增强了可测试性,提供了更标准化的设计,并为更多“Web 2.0”类型的网站打开了大门。

However, there are some significant drawbacks as well.

但是,也存在一些明显的缺点。

First, while it is easy to get a demo site going, the overall architectural model has a significant learning curve. When they say "Convention Over Configuration" it sounds good - until you realize that you have a book's-worth of convention to learn. Furthermore, it is often a bit maddening to figure out what is going on because you arerelying on magic rather than explicit calls. For example, that "Return View();" call above? The exact same call can be found in other Actions but they go to different places.If you understand the MVC conventionthen you know why this is done. However, it certainly doesn't qualify as an example of good naming or easily understandable code and it is much harder for new developers to pick up than Web Forms (this isn't just opinion: I had a summer intern learn Web Forms last year and MVC this year and the differences in productivity were pronounced - in favor of Web Forms). BTW, Rails is a bit better in this regard although Ruby on Rails features dynamically-named methods that take some serious getting-used-to as well.

首先,虽然让演示站点运行起来很容易,但整体架构模型具有显着的学习曲线。当他们说“约定优于配置”时,这听起来不错——直到你意识到你有一本书值得学习的约定。此外,它往往是有点郁闷弄清楚什么是对,因为你要依靠魔法,而不是显式调用。例如,“返回视图();” 上面打电话?在其他操作中可以找到完全相同的调用,但它们转到不同的位置。如果您了解MVC 约定那么你就知道为什么要这样做了。但是,它当然不能作为良好命名或易于理解的代码的示例,而且新开发人员比 Web Forms 更难掌握(这不仅仅是意见:去年我有一个暑期实习生学习 Web Forms和今年的 MVC 以及生产力的差异很明显 - 有利于 Web 表单)。顺便说一句,Rails 在这方面要好一些,尽管 Ruby on Rails 具有动态命名的方法,这些方法也需要一些认真的习惯。

Second, MVC implicitly assumes that you are building a classic CRUD-style web site. The architectural decisions and especially the code generators are all built to support this type of web application. If you are building a CRUD application and want to adopt a proven architecture (or simply dislike architecture design), then you should probably consider MVC. However, if you'll be doing more than CRUD and/or you are reasonably competent with architecture then MVC may feel like a straightHymanet until you really master the underlying routing model (which is considerably more complex than simply routing in a WebForms app). Even then, I've felt like I was always fighting the model and worried about unexpected outcomes.

其次,MVC 隐含地假设您正在构建一个经典的 CRUD 风格的网站。架构决策,尤其是代码生成器都是为了支持这种类型的 Web 应用程序而构建的。如果您正在构建 CRUD 应用程序并希望采用经过验证的架构(或者只是不喜欢架构设计),那么您可能应该考虑 MVC。但是,如果您要做的不仅仅是 CRUD 和/或您在架构方面有相当的能力,那么在您真正掌握底层路由模型(这比简单地在 WebForms 应用程序中进行路由要复杂得多)之前,MVC 可能会感觉像一件直筒外套。即便如此,我还是觉得我总是在与模型作斗争,并担心意外的结果。

Third, if you don't care for Linq(either because you are afraid that Linq-to-SQL is going to disappear or because you find Linq-to-Entities laughably over-produced and under powered) then you also don't want to walk this path since ASP.NET MVC scaffolding tools are build around Linq (this was the killer for me). Rails's data model is also quite clumsy compared to what you can achieve if you are experienced in SQL (and especially if you are well-versed in TSQL and stored procedures!).

第三,如果您不关心 Linq(因为您担心 Linq-to-SQL 会消失,或者因为您发现 Linq-to-Entities 可笑地过度生产且功能不足),那么您也不希望走这条路,因为 ASP.NET MVC 脚手架工具是围绕 Linq 构建的(这对我来说是杀手锏)。如果您在 SQL 方面有经验(尤其是如果您精通 TSQL 和存储过程!),Rails 的数据模型与您可以实现的模型相比也相当笨拙。

Fourth, MVC proponents often point out that MVC views are closer in spirit to the HTML/CSS/AJAX model of the web. For example, "HTML Helpers" - the little code calls in your vew page that swap in content and place it into HTML controls - are much easier to integrate with Javascript than Web Forms controls. However, ASP.NET 4.0 introduces the ability to name your controls and thus largely eliminates this advantage.

第四,MVC 支持者经常指出 MVC 视图在精神上更接近于 Web 的 HTML/CSS/AJAX 模型。例如,“HTML 帮助程序”——在您的视图页面中交换内容并将其放置到 HTML 控件中的小代码调用——与 Javascript 集成比 Web 窗体控件要容易得多。但是,ASP.NET 4.0 引入了命名控件的功能,因此在很大程度上消除了这一优势。

Fifth, MVC purists often deride Viewstate. In some cases, they are right to do so. However, Viewstate can also be a great tool and a boon to productivity. By way of comparison, handling Viewstate is mucheasier than trying to integrate third-party web controls in an MVC app. While control integration may get easier for MVC, all of the current efforts that I've seen suffer from the need to build (somewhat grody) code to link these controls back to the view's Controller class (that is - to work aroundthe MVC model).

第五,MVC 纯粹主义者经常嘲笑 Viewstate。在某些情况下,他们这样做是正确的。然而,Viewstate 也可以是一个很好的工具,可以提高生产力。相比之下,处理 Viewstate比尝试在 MVC 应用程序中集成第三方 Web 控件容易得多。虽然 MVC 的控件集成可能会变得更容易,但我所看到的所有当前工作都需要构建(有点粗糙)代码以将这些控件链接回视图的 Controller 类(即 -解决MVC 模型)。

Conclusions

结论

I like MVC development in many ways (although I prefer Rails to ASP.NET MVC by a long shot). I also think that it is important that we don't fall into the trap of thinking that ASP.NET MVC is an "anti-pattern" of ASP.NET Web Forms. They are different but not completely alien and certainly there is room for both.

我在很多方面都喜欢 MVC 开发(尽管从长远来看,我更喜欢 Rails 而非 ASP.NET MVC)。我还认为重要的是我们不要陷入认为 ASP.NET MVC 是 ASP.NET Web 窗体的“反模式”的陷阱。它们是不同的,但并非完全陌生,当然两者都有空间。

However, I prefer Web Forms development because, for most tasks, it is simply easier to get things done (the exception being generation of a set of CRUD forms). MVC also seems to suffer, to some extent, from an excess of theory.Indeed, look at the many questions asked here on SO by people who know page-oriented ASP.NET but who are trying MVC. Without exception, there is much gnashing of teeth as developers find that they can't do basic tasks without jumping through hoops or enduring a huge learning curve. Thisis what makes Web Forms superior to MVC in my book: MVC makes you pay a real world pricein order to gain a bit more testability or, worse yet, to simply be seen as coolbecause you are using the latest technology.

但是,我更喜欢 Web Forms 开发,因为对于大多数任务完成任务更容易(生成一组 CRUD 表单除外)。在某种程度上,MVC 似乎也受到过多理论的影响。事实上,看看那些了解面向页面的 ASP.NET 但正在尝试 MVC 的人在 SO 上提出的许多问题。毫无例外,当开发人员发现他们无法完成基本任务时,如果不跳过箍或忍受巨大的学习曲线,就会咬牙切齿。是什么使优于MVC Web窗体在我的书:MVC会让你付出了真实的世界价格,以便获得更多的可测性,或者还有更糟简单地被看作是冷静,因为你使用的是最新技术。

Update: I've been criticized heavily in the comments section - some of it quite fair. Thus, I have spent several months learning Rails and ASP.NET MVC just to make sure I wasn't really missing out on the next big thing! Of course, it also helps ensure that I provide a balanced and appropriate response to the question. You should know that the above response is a major rewrite of my initial answer in case the comments seem out of synch.

更新:我在评论部分受到了严厉批评 - 其中一些相当公平。因此,我花了几个月的时间学习 Rails 和 ASP.NET MVC,只是为了确保我不会真的错过下一件大事!当然,这也有助于确保我对问题提供平衡和适当的回答。您应该知道,如果评论似乎不同步,上述回复是对我最初答案的主要重写。

While I was looking more closely into MVC I thought, for a little while, that I'd end up with a major mea culpa. In the end I concluded that, while I think we need to spend a lot more energy on Web Forms architecture and testability, MVC really doesn't answer the call for me. So, a hearty "thank you" to the folks that provided intelligent critiques of my initial answer.

当我更仔细地研究 MVC 时,我想,有一段时间,我最终会犯下重大的错误。最后我得出的结论是,虽然我认为我们需要在 Web Forms 架构和可测试性上花费更多的精力,但 MVC 真的不适合我。因此,向那些对我最初的答案提供明智批评的人们表示衷心的“谢谢”。

As to those who saw this as a religious battleand who relentlessly engineered downvote floods, I don't understand why you bother (20+ down-votes within seconds of one another on multiple occasions is certainly not normal). If you are reading this answer and wondering if there is something truly "wrong" about my answer given that the score is far lower than some of the other answers, rest assured that it says more about a few people who disagree than the general sense of the community (overall, this one has been upvoted well over 100 times).

对于那些认为这是一场宗教War并无情地设计了反对票泛滥的人,我不明白你为什么要费心(多次在几秒钟内相互反对超过 20 票肯定是不正常的)。如果您正在阅读这个答案并想知道我的答案是否真的“错误”,因为分数远低于其他一些答案,请放心,它更多地说明了一些不同意的人,而不是一般意义上的社区(总体而言,该社区已被投票超过 100 次)。

The fact is that many developers don't care for MVC and, indeed, this is not a minority view (even within MS as the blogs seem to indicate).

事实是,许多开发人员并不关心 MVC,事实上,这不是少数人的观点(即使在 MS 中,正如博客所表明的那样)。

回答by Hugoware

MVC gives you more control over your output, and with that control comes greater risk of writing poorly designed HTML, tag soup, etc...

MVC 使您可以更好地控制您的输出,而这种控制带来了编写设计糟糕的 HTML、标签汤等的更大风险......

But at the same time, you have several new options you didn't have before...

但与此同时,你有几个以前没有的新选择......

  1. More control over the page and the elements within the page
  2. Less "junk" in your output, like the ViewState or excessively long IDs on elements (don't get me wrong, I like the ViewState)
  3. Better ability to do client side programming with Javascript (Web 2.0 Applications anyone?)
  4. Not just just MVC, but JsonResult is slick...
  1. 更好地控制页面和页面内的元素
  2. 减少输出中的“垃圾”,例如 ViewState 或元素上过长的 ID (别误会,我喜欢 ViewState)
  3. 更好地使用 Javascript 进行客户端编程(Web 2.0 应用程序有人吗?)
  4. 不仅仅是 MVC,而且 JsonResult 也很漂亮……

Now that's not to say that you can't do any of these things with WebForms, but MVC makes it easier.

这并不是说您不能用 WebForms 做这些事情,但 MVC 使它更容易。

I still use WebForms for when I need to quickly create a web application since I can take advantage of server controls, etc. WebForms hides all the details of input tags and submit buttons.

当我需要快速创建 Web 应用程序时,我仍然使用 WebForms,因为我可以利用服务器控件等。WebForms 隐藏了输入标签和提交按钮的所有细节。

Both WebForms and MVC are capable of absolute garbage if you are careless. As always, careful planning and well thought out design will result in a quality application, regardless if it is MVC or WebForms.

如果您不小心,WebForms 和 MVC 都可以成为绝对垃圾。与往常一样,无论是 MVC 还是 WebForms,仔细规划和深思熟虑的设计都会产生高质量的应用程序。

[Update]

[更新]

If it is any consolation as well, MVC is just a new, evolving technology from Microsoft. There has been many postings that WebForms will not only remain, but continue to be developed for...

如果这也有什么安慰的话,MVC 只是来自 Microsoft 的一项新的、不断发展的技术。有很多帖子说 WebForms 不仅会保留下来,而且还会继续为……

http://haacked.com

http://haacked.com

http://www.misfitgeek.com

http://www.misfitgeek.com

http://rachelappel.com

http://rachelappel.com

... and so on...

... 等等...

For those concerned about the route MVC is taking, I'd suggest giving "the guys" your feedback. They appear to be listening so far!

对于那些关心 MVC 所采取的路线的人,我建议给“伙计们”你的反馈。到目前为止,他们似乎一直在听!

回答by J Wynia

Most of the objections to ASP.NET MVC seems centered around the views, which are one of the most "optional" and modular bits in the architecture. NVelocity, NHaml, Spark, XSLT and other view engines can be easily swapped out(and it's been getting easier with every release). Many of those have MUCH more concise syntax for doing presentation logic and formatting, while still giving complete control over the emitted HTML.

大多数对 ASP.NET MVC 的反对似乎都集中在视图上,视图是体系结构中最“可选”和模块化的部分之一。NVelocityNHamlSpark、 XSLT 和其他视图引擎可以轻松换出(并且随着每个版本的发布都变得越来越容易)。其中许多具有更简洁的语法来执行表示逻辑和格式化,同时仍然可以完全控制发出的 HTML。

Beyond that, nearly every criticism seems to come down to the <% %> tagging in the default views and how "ugly" it is. That opinion is often rooted in being used to the WebForms approach, which just moves most of the classic ASP ugliness into the code-behind file.

除此之外,几乎所有的批评似乎都归结为默认视图中的 <% %> 标记以及它有多“丑陋”。这种观点通常植根于对 WebForms 方法的习惯,它只是将大部分经典的 ASP 丑陋转移到代码隐藏文件中。

Even without doing code-behinds "wrong", you have things like OnItemDataBound in Repeaters, which is just asaesthetically ugly, if only in a different way, than "tag soup". A foreach loop can be much easier to read, even with variable embedding in the output of that loop, particularly if you come to MVC from other non-ASP.NET technologies. It takes much less Google-fu to understand the foreach loop than to figure out that the way to modify that one field in your repeater is to mess with OnItemDataBound (and the rat's nest of checking if it's the right element to be changed.

即使没有做“错误”的代码隐藏,你也有像 Repeater 中的 OnItemDataBound 之类的东西,这美学上与“标签汤”一样丑陋,即使只是以不同的方式。foreach 循环可以更容易阅读,即使在该循环的输出中嵌入了变量,尤其是当您从其他非 ASP.NET 技术来到 MVC 时。理解 foreach 循环所需的 Google-fu 比找出修改中继器中该字段的方法是弄乱 OnItemDataBound (以及检查它是否是要更改的正确元素的老鼠窝)要少得多。

The biggest problem with ASP tag-soup-driven "spaghetti" was more about shoving things like database connections right in between the HTML.

ASP 标签汤驱动的“意大利面”的最大问题更多是关于在 HTML 之间插入数据库连接之类的东西。

That it happened to do so using <% %> is just a correlation with the spaghetti nature of classic ASP, not causation. If you keep your view logic to HTML/CSS/Javascript and the minimal logic necessary to do presentation, the rest is syntax.

它碰巧使用 <% %> 这样做只是与经典 ASP 的意大利面性质有关,而不是因果关系。如果您将视图逻辑保留为 HTML/CSS/Javascript 以及进行演示所需的最小逻辑,那么剩下的就是语法。

When comparing a given bit of functionality to WebForms, make sure to include all of the designer-generated C#, and the code-behind C# along with the .aspx code to be sure that the MVC solution is really not, in fact, much simpler.

将给定的功能与 WebForms 进行比较时,请确保包含所有设计器生成的 C# 和隐藏的 C# 以及 .aspx 代码,以确保 MVC 解决方案实际上并不简单得多.

When combined with judicious use of partial views for repeatable bits of presentation logic, it really can be nice and elegant.

当结合明智地使用部分视图来呈现可重复的表示逻辑位时,它真的可以很好很优雅。

Personally, I wish much of the early tutorial content focused more on this end of things than nearly exclusively on the test-driven, inversion of control, etc. While that other stuff is what the experts object to, guys in the trenches are more likely to object to the "tag soup".

就我个人而言,我希望早期的教程内容更多地集中在这方面,而不是几乎完全集中在测试驱动、控制反转等方面。虽然专家反对其他内容,但战壕中的人更有可能反对“标签汤”。

Regardless, this is a platform that is still in beta. Despite that, it's getting WAY more deployment and non-Microsoft developers building actual stuff with it than most Microsoft-beta technology. As such, the buzz tends to make it seem like it's further along than the infrastructure around it (documentation, guidance patterns, etc) is. It being genuinely usable at this point just amplifies that effect.

无论如何,这是一个仍处于测试阶段的平台。尽管如此,与大多数 Microsoft-beta 技术相比,它的部署和非 Microsoft 开发人员使用它构建实际内容的方式要多得多。因此,嗡嗡声往往使它看起来比周围的基础设施(文档、指导模式等)更进一步。在这一点上它真正可用只会放大这种效果。

回答by Todd Smith

<% if (Model.PreviousPost || Model.NextPost) { %>
    <div class="pager">
        <% if (Model.PreviousPost) { %>
            <span><% Html.ActionLink("<< " + Model.PreviousPost.Subject, "view")); %></span>
        <% } if (Model.NextPost) { %>
            <span><% Html.ActionLink(Model.NextPost.Subject + " >>", "view")); %></span>
        <% } %>
    </div>
<% } %>

You can make another post asking how to do this without including the embeded CSS.

您可以发另一篇文章询问如何在不包含嵌入式 CSS 的情况下执行此操作。

NOTE: ViewData.Model becomes Model in the next release.

注意:ViewData.Model 在下一个版本中变为 Model。

And with the aid of a user control this would become

在用户控制的帮助下,这将变成

<% Html.RenderPartial("Pager", Model.PagerData) %>

where PagerData is initialized via an anonymous constructor in the action handler.

其中 PagerData 是通过操作处理程序中的匿名构造函数初始化的。

edit: I'm curious what your WebForm implementation would look like for this problem.

编辑:我很好奇你的 WebForm 实现会如何解决这个问题。

回答by Tom Anderson

I am not sure at what point people stopped caring about their code.

我不确定人们从什么时候开始不再关心他们的代码。

HTML is the most public display of your work, there are a LOT of developers out there who use notepad, notepad++, and other plain text editors to build a lot of websites.

HTML 是您作品最公开的展示方式,有很多开发人员使用记事本、记事本++和其他纯文本编辑器来构建大量网站。

MVC is about getting control back from web forms, working in a stateless environment, and implementing the Model View Controller design pattern without all the extra work that normally takes place in an implementation of this pattern.

MVC 是关于从 Web 表单取回控制权,在无状态环境中工作,并实现模型视图控制器设计模式,而无需在此模式的实现中通常发生的所有额外工作。

If you want control, clean code, and to use MVC design patterns, this is for you, if you don't like working with markup, don't care about how malformed your markup gets, then use ASP.Net Web Forms.

如果您想要控制、干净的代码并使用 MVC 设计模式,那么这适合您,如果您不喜欢使用标记,也不关心标记的格式如何,那么请使用 ASP.Net Web 窗体。

If you don't like either, you are definitely going to be doing just about as much work in the markup.

如果你不喜欢任何一个,你肯定会在标记中做同样多的工作。

EDITI Should also state that Web Forms and MVC have their place, I was in no way stating that one was better than the other, only that each MVC has the strength of regaining control over the markup.

编辑我还应该声明 Web 窗体和 MVC 有它们的位置,我绝不是说一个比另一个更好,只是每个 MVC 都有重新控制标记的力量。

回答by tvanfosson

I think you are missing some things. First, there's no need for the Response.Write, you can use the <%= %>tags. Second, you can write your own HtmlHelper extensions to do common actions. Third, a little bit of formatting helps a lot. Fourth, all of this would probably be stuck in a user control to be shared between several different views and thus the overall mark up in the main view is cleaner.

我认为你错过了一些东西。首先,不需要 Response.Write,您可以使用<%= %>标签。其次,您可以编写自己的 HtmlHelper 扩展来执行常见操作。第三,一点点格式化有很大帮助。第四,所有这些都可能被困在一个用户控件中,以便在几个不同的视图之间共享,因此主视图中的整体标记更清晰。

I'll grant you that the mark up is still not as neat as one would like, but it could be cleaned up considerably through the use of some temporary variables.

我会承认标记仍然没有人们想要的那么整洁,但是可以通过使用一些临时变量将其清理干净。

Now, that's not so bad and it would be even better if I didn't have to format it for SO.

现在,这还不错,如果我不必为 SO 格式化它会更好。

 <%
    var PreviousPost = ViewData.Model.PreviousPost;
    var NextPost = ViewData.Model.NextPost;

    // Display the "Next and Previous" links
    if (PreviousPost != null || NextPost != null)
    {
  %>

 <div>

        <%= PreviousPost == null
                ? string.Empty
                : Html.ActionLinkSpan("<< " + PreviousPost.Subject,
                                "view",
                                new { id = PreviousPost.Id },
                                new { style = "float: left;" } ) %>
          <%= NextPost == null
                ? string.Empty
                : Html.ActionLinkSpan( NextPost.Subject + " >>",
                                   "view",
                                    new { id = NextPost.Id },
                                    new { style = "float: right;" } ) %>

  <div style="clear: both;" />
  </div>

  <% } %>

回答by dkretz

The big deal with MVC is that it's a conceptual framework that has been around a long time, and it has proven itself as a productive, powerful way to build both web applications and workstation applications that scale horizontally and vertically. It goes directly back to the Alto and Smalltalk. Microsoft is late to the party. What we have now with ASP.NET MVC is really primitive, because there's so much catching up to do; but damn, they're pouring out new releases fast and furiously.

MVC 的重要之处在于它是一个已经存在很长时间的概念框架,并且已经证明它是一种高效、强大的方式来构建水平和垂直扩展的 Web 应用程序和工作站应用程序。它直接回到 Alto 和 Smalltalk。微软迟到了。我们现在拥有的 ASP.NET MVC 真的很原始,因为还有很多事情要做;但是该死的,他们正在快速而疯狂地发布新版本。

What was the big deal with Ruby on Rails? Rails is MVC. Developers have been converting because, by word of mouth, it's become the way for programmers to be productive.

Ruby on Rails 有什么大不了的?Rails 是 MVC。开发人员一直在转换,因为通过口耳相传,它已成为程序员提高生产力的方式。

It's a huge deal; MVC and the implicit endorsement of jQuery are tipping points for Microsoft accepting that platform-neutral is critical. And what's neutral about it, is that unlike Web Forms, Microsoft can't lock you in conceptually. You can take all your C# code and reimplement in another language entirely (say PHP or java - you name it) because it's the MVC concept that's portable, not the code itself. (And think how huge it is that you can take your design and implement it as a workstation app with little code change, and no design change. Try that with Web Forms.)

这是一个大问题;MVC 和对 jQuery 的隐性认可是微软接受平台中立至关重要的转折点。它的中立之处在于,与 Web Forms 不同的是,Microsoft 无法在概念上锁定您。您可以将所有 C# 代码完全用另一种语言重新实现(比如 PHP 或 java - 您可以命名),因为它是可移植的 MVC 概念,而不是代码本身。(想想你可以把你的设计作为一个工作站应用程序来实现它是多么巨大,只需很少的代码更改,没有设计更改。尝试使用 Web 表单。)

Microsoft has decided that Web Forms will not be the next VB6.

Microsoft 已决定 Web Forms 不会成为下一个 VB6。

回答by Shiju

Please have a look at Rob Conery's post I Spose I'll Just Say It: You Should Learn MVC

请看一下 Rob Conery 的帖子我说我就说:你应该学习 MVC

回答by Kevin Pang

The two main advantages of the ASP.NET MVC framework over web forms are:

ASP.NET MVC 框架相对于 Web 表单的两个主要优点是:

  1. Testability- The UI and events in web forms are next to impossible to test. With ASP.NET MVC, unit testing controller actions and the views they render is easy. This comes with a cost in up-front development cost, but studies have shown that this pays off in the long run when it comes time to refactor and maintain the app.
  2. Better control over rendered HTML- You state that you don't care about the rendered HTML because nobody looks at it. That's a valid complaint if that were the only reason to have properly formatted HTML. There are numerous reasons for wanting properly formatted HTML including: SEO, the ability to use id selectors more often (in css and javascript), smaller page footprints due to lack of viewstate and ridiculously long ids (ctl00_etcetcetc).
  1. 可测试性- Web 表单中的 UI 和事件几乎无法测试。使用 ASP.NET MVC,单元测试控制器操作和它们呈现的视图很容易。这带来了前期开发成本,但研究表明,从长远来看,当需要重构和维护应用程序时,这是值得的。
  2. 更好地控制呈现的 HTML- 您声明您不关心呈现的 HTML,因为没有人会查看它。如果这是正确格式化 HTML 的唯一原因,那么这是一个有效的抱怨。需要正确格式化的 HTML 的原因有很多,包括:SEO、更频繁地使用 id 选择器的能力(在 css 和 javascript 中)、由于缺乏 viewstate 和长得可笑的 id(ctl00_etc 等)而导致的较小页面占用。

Now, these reasons don't really make ASP.NET MVC any better or worse than web forms in a black-and-white sort of way. ASP.NET MVC has its strengths and weaknesses, just like web forms. However, the majority of complains about ASP.NET MVC seem to stem from a lack of understanding on how to use it rather than actual flaws in the framework. The reason your code doesn't feel right or look right might be because you have several years of web forms experience under your belt and only 1-2 months of ASP.NET MVC experience.

现在,这些原因并没有真正使 ASP.NET MVC 比黑白形式的 Web 表单更好或更差。ASP.NET MVC 有其优点和缺点,就像 Web 表单一样。然而,大多数对 ASP.NET MVC 的抱怨似乎源于对如何使用它缺乏了解,而不是框架中的实际缺陷。您的代码感觉不正确或看起来不正确的原因可能是因为您有几年的 Web 表单经验,而只有 1-2 个月的 ASP.NET MVC 经验。

The problem here isn't so much that ASP.NET MVC rocks or sucks, it's that it's new and there's very little agreement as to how to use it correctly. ASP.NET MVC offers much more fine-grained control over what's occurring in your app. That can make certain tasks easier or harder depending on how you approach them.

这里的问题不在于 ASP.NET MVC 摇摆不定或糟糕透顶,而是它是新的,并且对于如何正确使用它几乎没有达成一致。ASP.NET MVC 对应用程序中发生的事情提供了更细粒度的控制。这可以使某些任务更容易或更难,具体取决于您如何处理它们。

回答by Papa Burgundy

Hey, I've been struggling with switching to MVC as well. I am absolutely not a fan of classic ASP and MVC rendering reminds me a lot of those days. However, the more I use MVC, the more it grows on me. I am a webforms guy (as many are) and spent the past several years getting used to working with datagrids, etc. With MVC that is taken away. HTML Helper classes are the answer.

嘿,我也一直在努力切换到 MVC。我绝对不是经典 ASP 的粉丝,MVC 渲染让我想起了很多那些日子。然而,我使用 MVC 的次数越多,它对我的​​影响就越大。我是一个 webforms 人(和很多人一样)并且在过去的几年里习惯于使用 datagrids 等。MVC 被带走了。HTML Helper 类就是答案。

Just recently I spent 2 days trying to figure out the best way to add paging to a "grid" in MVC. Now, with webforms I could whip this out in no time. But I will say this... once I had the paging helper classes built for MVC, it became extremely simple to implement. To me, even easier than webforms.

就在最近,我花了 2 天时间试图找出将分页添加到 MVC 中的“网格”的最佳方法。现在,有了网络表单,我可以立即解决这个问题。但我会这样说...一旦我为 MVC 构建了分页助手类,实现起来就变得非常简单。对我来说,甚至比 webforms 更容易。

That being said, I think that MVC will be much more developer friendly when there are a consistent set of HTML Helpers out there. I think we are going to start seeing a ton of HTML helper classes pop up on the web in the near future.

话虽如此,我认为当有一组一致的 HTML 帮助程序时,MVC 对开发人员会更加友好。我认为在不久的将来,我们将开始看到大量的 HTML 帮助类在网络上出现。