MVC4剃须刀 - @ Html.DisplayFor不具约束力的模型 [英] MVC4 Razor - @Html.DisplayFor not binding to model

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

问题描述

我试图找到我的脚MVC4剃刀和我坚持这个简单的问题。

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框架错过。不只是在助手,如 HiddenFor DisplayFor TextBoxFor - 但究竟如何框架设置自动收集和验证这些输入。神奇的是所有HTML5的数据 - *属性完成。看着input标签产生的,有要在数据-VAL 数据val-的形式,一些额外的属性时,你会发现需要,也许对于某些类型的附加数据的属性,例如Numerics的是数据-VAL-号

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.

公布数据的实​​际收集是从名称属性的体现。这是应了映射到在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 当你想显示的记录,但不允许他们进行editted。

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.

修改

这一观点的目的是为了让用户提交给数据库之前查看数据。任何想法我怎么能做到这一点?

您可以用 HiddenFor 二重奏和 DisplayFor 做到这一点。使用 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剃须刀 - @ Html.DisplayFor不具约束力的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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