MVC4 Razor - @Html.DisplayFor 未绑定到模型 [英] MVC4 Razor - @Html.DisplayFor not binding to model

查看:28
本文介绍了MVC4 Razor - @Html.DisplayFor 未绑定到模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用 MVC4 Razor 找到我的脚,但我被这个简单的问题困住了.

I am trying to find me feet with MVC4 Razor and I'm stuck with this simple problem.

当我使用@Html.DisplayFor 时,模型总是作为 NULL 返回,但是当我使用 @Html.TextBoxFor 时,这个模型是完全填充的,我错过了什么?

When I use @Html.DisplayFor the model is always sent back as NULL, but when I use @Html.TextBoxFor this model is fully populated, what am I missing?

提前致谢

推荐答案

这是很多人在 asp.net mvc 框架中忽略的常见问题.不仅是诸如 HiddenForDisplayForTextBoxFor 之类的帮助器的不同,还有框架如何设置自动收集和验证这些输入.魔术是通过 HTML5 的 data-* 属性完成的.在查看生成的输入标记时,您会注意到将有一些额外的属性,形式为 data-valdata-val-required,也许还有一些类型的附加数据属性,例如数字将是 data-val-number.

This is a common issue that many people miss in the asp.net mvc framework. Not just the difference in the helpers such as HiddenFor, DisplayFor, TextBoxFor - but how exactly the framework sets up automatically collecting and validating these inputs. The magic is all done with HTML5's data-* attributes. You will notice when looking at the input tag generated that there are going to be some extra properties in the form of data-val, data-val-required, and perhaps some additional data properties for types, for example numerics would be data-val-number.

这些数据属性允许 jQuery 扩展 jquery.validate.unobtrusive.js 解析 DOM,然后决定验证哪些字段或生成错误消息.

These data attributes allow the jQuery extension jquery.validate.unobtrusive.js to parse the DOM and then decide which fields to validate or generate error messages.

发布数据的实​​际集合反映在 name 属性中.这是应该映射到 c# 或 vb [HttpPost] 方法中的模型的内容.

The actual collection of posted data is reflected from the name property. This is what should map up to the model that is in the c# or vb [HttpPost] method.

当您想提供用户不需要知道的已发布数据时,请使用 HiddenFor.

Use HiddenFor when you want to provide posted data that the user does not need to be aware of.

当您想显示记录但不允许编辑它们时,请使用 DisplayFor.

Use DisplayFor when you want to show records but not allow them to be editted.

当您希望允许用户输入或允许用户编辑字段时,请使用 TextBoxFor.

Use TextBoxFor when you want to allow user input or allow the user to edit a field.

编辑

这个视图的目的是让用户能够在将数据提交到数据库之前查看数据.有什么想法可以实现吗?"

您可以使用 HiddenForDisplayFor 的组合来实现这一点.使用 HiddenFor 准备发布值,并使用 DisplayFor 显示这些值.

You could accomplish this with a duo of HiddenFor and DisplayFor. Use HiddenFor to have the values ready to be posted, and DisplayFor to show those values.

这篇关于MVC4 Razor - @Html.DisplayFor 未绑定到模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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