MVC 发布值
在 asp.net MVC 应用程序中,我们有一个机制,当我们提交时 表单,如果值有任何问题(验证失败), 表单显示回来并保持旧值。这是怎么发生的? 这些值保存在哪里?或者他们从 FormCollection 收集。
我们将不胜感激。
问候 帕明德
In asp.net MVC application we have mechanism where, when we submit
a form and if there is any problem with the values (validation fails),
the form is displayed back maintaining old values. How does it happen ?
Where are these values kept ? or they collected from FormCollection.
Help will be apprititated.
Regards
Parminder
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这实际上取决于您如何设置控制器操作和视图,因为 ASP.NET MVC 在多个位置查找值。
您认为它使用 FormCollection 的假设有点错误,因为 FormCollection 是您的控制器 Action 作为参数接收的东西,并且与您的视图完全分开,在视图中实际最终显示值。
在 1.0 中,默认情况下,视图的编辑模板在大多数 HtmlHelpers 上使用第二个参数,例如:
这将从绑定的模型对象中提取旧值。因此,如果您明确验证失败并返回一个 View(object),则将从该对象中提取值。不过,如果您显式地使验证失败,例如:
那么 HtmlHelper 代码可能会导致错误,因为没有绑定模型。
如果您完全省略第二个参数,例如:
该值将从发布(Request.Form)值中提取。
It really depends on how you set up your Controller Actions and your Views, because ASP.NET MVC looks in multiple places for the values.
Your assumption that it uses the FormCollection is kind of wrong, since the FormCollection is something that your controller Action takes in as a parameter and is totally separate from your View, where the values actually end up being displayed.
In 1.0, by default, the Edit template for views uses the 2nd parameter on most of the HtmlHelpers, like:
This would have the old value pulled from the bound model object. So if you explicitly fail validation and return a View(object), the values would be pulled from that object. Still, if you are explicitly failing validation like:
Then the HtmlHelper code will likely result in an error, because no Model was bound.
If you completely leave off the 2nd parameter, like:
The value will be pulled from the post (Request.Form) values.
一种方法是使用 ModelState.AddModelError
可以找到有关 MVC 错误处理的好教程 此处
One way to do it is to use ModelState.AddModelError
A good tutorial on MVC Error handling can be found here
您可以通过返回带有数据的视图来做到这一点
X 是您需要返回的数据
You can do that by returning the view with tha data
X is the data u need to return