asp.net c# MVC:我如何在没有 ViewState 的情况下生活?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2230519/
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
asp.net c# MVC: How do I live without ViewState?
提问by Mark Redman
I am just looking into converting WebForms to MVC:
我只是想将 WebForms 转换为 MVC:
In .net MVC, what concepts make ViewState something thats not required?
在 .net MVC 中,哪些概念使 ViewState 成为不需要的东西?
If a form is posted back on iteself etc (ie a postback)? how does the page/usercontrol maintain its state?
如果表单在 iteself 等上回发(即回发)?页面/用户控件如何保持其状态?
What tricks are people doing to maintain some kind of state and not resort to session state?
人们用什么技巧来维护某种状态而不是诉诸会话状态?
Surely, a completely stateless environment cant exist?
当然,一个完全无状态的环境不能存在吗?
采纳答案by Rob Fonseca-Ensor
But of course it can. In fact, the web isstateless. Any thoughts to the contrary are the aberration, in fact.
但当然可以。事实上,网络是无状态的。事实上,任何相反的想法都是偏差。
Web Controls are gone in MVC. There are no events firing on the server side. This is replaced by two different mechanisms--URLs and POSTing form data. Proper use of these will replace your need for the ViewState.
Web 控件在 MVC 中消失了。服务器端没有事件触发。这被两种不同的机制取代——URL 和 POST 表单数据。正确使用这些将取代您对 ViewState 的需求。
In a conventional ASP.NET web application, you would place a LinkButton on your webpage that would perform function X. ASP.NET would stick lots of ViewState cruft, javascript and other stuff into the webpage so that, when the user clicks on the button and "posts back" to the website (by submitting a form nobody knows existed), ASP.NET reconstructs what happened and determines a particular button event handler must be executed.
在传统的 ASP.NET Web 应用程序中,您将在网页上放置一个 LinkButton 来执行功能 X。ASP.NET 会将大量 ViewState cruft、javascript 和其他内容粘贴到网页中,以便当用户单击按钮时并“回发”到网站(通过提交一个没人知道存在的表单),ASP.NET 重构发生的事情并确定必须执行特定的按钮事件处理程序。
In MVC, you construct your link to access a particular route. The route describes what the user wishes to do--/Users/Delinquent/Index (show a list of all delinquent users). The routing system in MVC determines which Controller will handle this route and which method on that controller will execute. Any additional information can be transmitted to the controller method by URL query string values (?Page=5 for the 5th page of delinquents).
在 MVC 中,您可以构建访问特定路由的链接。路由描述了用户希望做什么——/Users/Delinquent/Index(显示所有拖欠用户的列表)。MVC 中的路由系统确定哪个控制器将处理此路由以及该控制器上的哪个方法将执行。任何附加信息都可以通过 URL 查询字符串值传输到控制器方法(?Page=5 为第 5 页的拖欠)。
In addition to URLs, you can use HTML forms to POST back more complex information (such as a form's worth of data) or things that won't fit in a query string, such as a file.
除了 URL 之外,您还可以使用 HTML 表单来回传更复杂的信息(例如表单的数据)或不适合查询字符串的内容,例如文件。
So you "maintain" state via query strings and form POST values. You'll find that, in fact, there isn't that much state to maintain in the end. In fact, having to maintain lots of state is a good indication that your design is lacking or that you're trying to do something that doesn't fit a website model.
因此,您可以通过查询字符串“维护”状态并形成 POST 值。你会发现,事实上,最终没有那么多状态需要维护。事实上,必须维护大量状态是一个很好的迹象,表明您的设计缺乏或您正在尝试做一些不适合网站模型的事情。
回答by Tamas Czinege
The state is the model which is in the database. You can carefully cache the database to reduce page load times.
状态是数据库中的模型。您可以小心地缓存数据库以减少页面加载时间。
回答by Rob Fonseca-Ensor
viewstate is just a big, ugly hidden form field.
viewstate 只是一个又大又丑的隐藏表单域。
Write out your own hidden form fields, and encrypt them if you have to.
写出您自己的隐藏表单字段,并在必要时对其进行加密。
Fortunately, there's no longer any simple way to dump lots and lots of data into the page, so you have to be judicious about what you want to save.
幸运的是,不再有任何简单的方法可以将大量数据转储到页面中,因此您必须明智地选择要保存的内容。
回答by Amr Elgarhy
Auto generated view state does not exist in MVC, but you can write your own simply using hidden fields,
MVC 中不存在自动生成的视图状态,但您可以使用隐藏字段编写自己的视图状态,
In MVC you will not see a lot of encrypted chars at the top of the page which you don't need most of them.
在 MVC 中,您不会在页面顶部看到很多不需要的加密字符。
回答by Robert Harvey
If a form is posted back on itself etc (ie a postback)? how does the page/usercontrol maintain its state? What tricks are people doing to maintain some kind of state and not resort to session state?
如果表单被回发到自身等(即回发)?页面/用户控件如何保持其状态?人们用什么技巧来维护某种状态而不是诉诸会话状态?
The posted ViewData (or strongly-typed object bound to the page) can be pushed out to the view again. See "Integrating Validation and Business Rule Logic with Model Classes" in this page.It shows how you can post a form, validate it, and return the fields back to the form if an error occurs.
发布的 ViewData(或绑定到页面的强类型对象)可以再次推送到视图中。请参阅本页中的“将验证和业务规则逻辑与模型类集成” 。它展示了如何发布表单、验证它并在发生错误时将字段返回给表单。
In .net MVC, what concepts make ViewState something thats not required?
在 .net MVC 中,哪些概念使 ViewState 成为不需要的东西?
回答by Nathan Taylor
Some related questions:
一些相关问题:
In most traditional web languages the concept of a stateful environment is actually quite uncommon. ASP.NET Webforms is an exception to the rule and it creates that exception by reinventing a lot of standards. The goal behind Webforms is essentially to abstract the concept of HTML and web development in general so that the line between desktop application and web application blurs from a development standpoint. What this generally tends to mean is that the solution that ASP.NET Webforms provides, although effective, is a Hyman-of-all-trades implementation which results in some very verbose output that works well enough to satisfy most. Conversely, the core advantage of ASP.NET MVC is that it gives HTML output control back to the developer and allows them to create strongly-architected, RESTfulweb applications that are better defined and cleaner in their implementation and presentation- despite sacrificing some level of convenience.
在大多数传统 Web 语言中,有状态环境的概念实际上并不常见。ASP.NET Webforms 是该规则的一个例外,它通过重新发明许多标准来创建该例外。Webforms 背后的目标本质上是抽象 HTML 和 Web 开发的概念,以便从开发的角度来看桌面应用程序和 Web 应用程序之间的界限变得模糊。这通常意味着 ASP.NET Webforms 提供的解决方案虽然有效,但它是一个万事通的实现,它会产生一些非常冗长的输出,足以满足大多数人的需求。相反,ASP.NET MVC 的核心优势是它将 HTML 输出控制权交还给开发人员,并允许他们创建强架构的RESTful尽管牺牲了一定程度的便利性,但在实现和呈现方面定义更清晰、更清晰的 Web 应用程序。
Arguably, one of the largest drawbacks of the Webforms model is the ViewState because it clutters the output, increases the page size dramatically in certain scenarios, and is often the equivalent of using a Hymanhammer to hang a picture. Rather than trying to make use of ViewState in your MVC application (or anything resembling it), you should begin to use patterns which explicitly control the fields in your forms and optimize your input and output operations with only the most relevant data. In addition to the changes in markup, you will also learn to build better designed solutions that can be exposed within your application and externally.
可以说,Webforms 模型的最大缺点之一是 ViewState,因为它使输出混乱,在某些情况下会显着增加页面大小,并且通常相当于使用手提钻挂一张图片。与其尝试在您的 MVC 应用程序(或任何类似它的东西)中使用 ViewState,您应该开始使用模式来显式控制表单中的字段并仅使用最相关的数据优化您的输入和输出操作。除了标记的变化,您还将学习构建设计更好的解决方案,这些解决方案可以在您的应用程序内和外部公开。
The number one comparison I like to make is simply: Webforms builds Web Pages, but MVC builds Web Applications. If your day-to-day work is primarily building pieces of a website, or adding small chunks of functionality, you will often find Webforms to be much easier and less time consuming; on the other hand, if you want to build a complete application that is testable, scalable, and flexible, MVC is your calling.
我喜欢做的第一个比较很简单:Webforms 构建网页,而 MVC 构建 Web 应用程序。如果您的日常工作主要是构建网站的各个部分或添加小块功能,您通常会发现 Webforms 更容易且耗时更少;另一方面,如果您想构建一个完整的可测试、可扩展和灵活的应用程序,MVC 是您的召唤。
回答by Arthis
Actually it does. You have to forget about the way persistance was made up with the viewstate.
事实上确实如此。您必须忘记持久性是由视图状态构成的。
You have also to convert in your mind postback onto a page to "call to a controller". This way things will be easier to understand afterwards. Instead of calling a page , you're calling a controller which returns a view. So either your are building your whole "page" again and again on every call, or you decide to deal only with what is really impacted by the action. If the button is changing a div, why reload the entire page. Just make you call to your controller and return what should be the new data in your div.
您还必须在脑海中将回发转换为页面以“调用控制器”。这样事情之后会更容易理解。您不是调用 page ,而是调用返回视图的控制器。因此,要么您在每次调用时一次又一次地构建整个“页面”,要么您决定只处理真正受该操作影响的内容。如果按钮正在更改 div,为什么要重新加载整个页面。只需让您调用控制器并返回 div 中的新数据即可。
for example let's imagine a master/detail scenario:
例如,让我们想象一个主/细节场景:
<h2>Groups</h2>
<div id="GroupList">
</div>
<div id="GroupDetail" title="Detail Group">
</div>
The list of group is loaded once in the div and there is an ajax call possible to a controller for each item of the list of group :
组列表在 div 中加载一次,并且可以对组列表中的每个项目的控制器进行 ajax 调用:
<%= Ajax.ActionLink("Edit", "DetailLocalisationGroup",
new { id = group.Id },
new AjaxOptions() {
UpdateTargetId = "DetailLocalisationGroup",
OnSuccess = "InitialisationDetailGroup" })%>
which calls this action DetailLocalisationGroup which is to feed the div GroupDetail with html.
它调用这个动作 DetailLocalisationGroup ,它是用 html 提供 div GroupDetail 。
[AcceptVerbs("POST")]
public ActionResult DetailLocalisationGroup(int id)
{
LocalisationGroup group = servicelocalisation.GetLocalisationGroup(id);
return View("DetailGroup", group);
}
There is now a form in the div, and when pushing the submit button of this form, we just send the information we really need to a controller which would then save the data in the database.
现在div中有一个表单,当按下这个表单的提交按钮时,我们只是将我们真正需要的信息发送到控制器,然后控制器将数据保存在数据库中。
During all these events, the GroupList was filled with stuff that was displayed on the client screen, but no interaction was needed there and so why bother oneself with a viewstate for these...
在所有这些事件中,GroupList 充满了显示在客户端屏幕上的东西,但那里不需要交互,所以为什么要为这些东西费心思的视图状态......
回答by Mark Brittingham
MVC has some advantages over WebForms but it also has some disadvantages as well as I covered detail in this answer. I think the fundamental question that you have to ask yourself is whether ViewState is a problemfor you now - and is it such a problem that you must rewrite your application? If not, then Learning MVC is a worthy goal (it really is quite cool) but not one that I'd risk business for.
MVC 比 WebForms 有一些优点,但它也有一些缺点,我在这个答案中详细介绍了。我认为您必须问自己的基本问题是 ViewState现在对您来说是否是一个问题-是否是您必须重写应用程序的问题?如果没有,那么学习 MVC 是一个有价值的目标(它真的很酷)但不是我愿意为之冒险的目标。
With that being said, ViewState can actually be disabled in a surprisingly large number of cases. It is used primarily to persist the value of controls through a post-back. So, for example, if you have a text box whose value you must check on the server side as well as a bunch of other fields, ViewState will let you handle the post-back, catch the error (and show a label) and then return the user to the form with all of their entries intact. However, if a form is onlygoing to be filled out and posted back and you'll then be redirecting to another page, you can safely disable it.
话虽如此,实际上可以在大量情况下禁用 ViewState。它主要用于通过回发保持控件的值。因此,例如,如果您有一个文本框,您必须在服务器端检查其值以及一堆其他字段,ViewState 将让您处理回发、捕获错误(并显示标签)然后将用户返回到其所有条目完好无损的表单。但是,如果表单只是要填写并回发,然后您将重定向到另一个页面,则可以安全地禁用它。
Finally, you ask what people are doing to avoid Session state. Is there a reason to avoid session state? Surely you don't want much information there but avoiding it altogether is really not necessary and, in fact, will cost you one of the most powerful tools in your arsenal.
最后,你问人们正在做什么来避免会话状态。是否有理由避免会话状态?当然,您不想要太多信息,但完全避免它确实没有必要,事实上,这将使您失去武器库中最强大的工具之一。
回答by Godeke
Consider the fact that the REST movement in web programming is predicated on the idea that state is badfor a program. The Wikipedia has a decent description with references: http://en.wikipedia.org/wiki/Representational_State_Transfer
考虑这样一个事实,即 Web 编程中的 REST 运动是基于状态对程序不利的想法。维基百科有一个不错的描述和参考:http: //en.wikipedia.org/wiki/Representational_State_Transfer
Coming from tranditional ASP.NET and the rich event model it provides, MVC can be quite jarring. It doesrequire managing some things that were invisible to you before, but I think that the value in terms of testability (REST pages can be triggered easily without creating a complex viewstate and by definition the server isn't holding state so I can test a page/feature in isolation) offsets the learning curve.
来自传统的 ASP.NET 和它提供的丰富的事件模型,MVC 可能非常刺耳。它确实需要管理一些你以前不可见的东西,但我认为在可测试性方面的价值(可以轻松触发 REST 页面而无需创建复杂的视图状态,并且根据定义服务器不保持状态,因此我可以测试页面/功能隔离)抵消了学习曲线。
For some discussion of MVC in ASP.NET and REST: http://blog.wekeroad.com/2007/12/06/aspnet-mvc-using-restful-architecture/
有关 ASP.NET 和 REST 中 MVC 的一些讨论:http: //blog.wekeroad.com/2007/12/06/aspnet-mvc-using-restful-architecture/
回答by Rune
All of the answers saying that ASP.NET MVC does not use state are pretty much correct. But ASP.NET MVC does in fact use some state, although it does not work anything like ViewState.
说 ASP.NET MVC 不使用状态的所有答案都非常正确。但是 ASP.NET MVC 实际上确实使用了一些状态,尽管它不像 ViewState 那样工作。
Usually, when someone POSTs data to your application, you will want to validate the data and display an error if the data are not valid. However, if you just return the page containing the error message immediately, when the user hits F5 to reload the page, the data will be resubmitted. This is usually not what you want. Thus, when you realize that the data POSTed are not valid, you want to tell the users to GET the page (or perhaps another page) and show an error message. You do that by returning an HTTP Redirect status code. However, once the user's GET request comes in, how do you know what error message to display? You will have to somehow remember this from the time you (the server) are handling the POST until you are handling the GET.
通常,当有人向您的应用程序 POST 数据时,您需要验证数据并在数据无效时显示错误。但是,如果您只是立即返回包含错误消息的页面,那么当用户按 F5 重新加载页面时,数据将被重新提交。这通常不是您想要的。因此,当您意识到发布的数据无效时,您希望告诉用户获取页面(或者可能是另一个页面)并显示错误消息。您可以通过返回 HTTP 重定向状态代码来实现。但是,一旦用户的GET请求进来了,你怎么知道要显示什么错误信息呢?从您(服务器)处理 POST 到处理 GET,您必须以某种方式记住这一点。
To do this you use an ASP.NET MVC feature called TempData. This is actually just a wrapper around Session which ensures that whatever you shove into the TempData dictionary will stay there until the next request and no longer.
为此,您可以使用名为 TempData 的 ASP.NET MVC 功能。这实际上只是 Session 的一个包装器,它确保您放入 TempData 字典的任何内容都将保留在那里,直到下一个请求并且不再存在。