关于Asp.Net MVC Helper Html.Hidden

时间:2011-10-24 17:00:11

标签: .net asp.net-mvc asp.net-mvc-3 asp.net-mvc-2

我有以下型号

Public Class BaseViewModel

Public Property Id as integer
Public Property Title As String

<DisplayName("Creation Date"), Required(), ScaffoldColumn(False)>
Public Property DateCreation As String
<DisplayName("Creation User"), Required(), ScaffoldColumn(False)>
Public Property UserCreation As String
<DisplayName("Modification Date"), ScaffoldColumn(False)>
Public Property DateModification As String
<DisplayName("Modification User"), ScaffoldColumn(False)>
Public Property UserModification As String

End Class

我创建了一个名为BaseViewModel的部分视图,其中包含以下HTML

<div id="Detail-Item" class="hidden">
@Using Html.BeginForm("Save", "Agency", Nothing, FormMethod.Post, New With {.id = "Detail-form"})
@<fieldset>
    <legend>Agency</legend>
    @Html.ValidationSummary()
    <div class="editor-label"> 
        @Html.LabelFor(Function(model) model.Id):
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(Function(model) model.Id, New With {.class = "textbox-id input-key textbox-inactive", .data_field = "Id", .readonly = "readonly"})    
        @Html.ValidationMessageFor(Function(model) model.Id, "*")
    </div>
    <div class="editor-label">
        @Html.LabelFor(Function(model) model.Title):
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(Function(model) model.Title, New With {.class = "textbox-name input-text focus", .data_field = "Title"})
        @Html.ValidationMessageFor(Function(model) model.Title, "*")
    </div>

    <div class="hidden">
        @Html.Hidden("UserCreation", String.Empty, New With {.class = "input-audituser", .data_field = "UserCreation"})
        @Html.Hidden("UserModification", String.Empty, New With {.class = "input-audituser", .data_field = "UserModification"})
        @Html.Hidden("DateCreation", String.Empty, New With {.class = "input-auditdate", .data_field = "DateCreation"})
        @Html.Hidden("DateModification", String.Empty, New With {.class = "input-auditdate", .data_field = "DateModification"})
    </div>
</fieldset>
End Using
</div>

要渲染此视图,我正在使用@ html.EditForModel。我的问题是,即使我使用Html.Hidden进行DateCreation和UserCreation模型属性,为这些字段生成的Html也包含“必需”数据验证属性。

这是应该的方式吗?如果是的话怎么可以避免呢?

2 个答案:

答案 0 :(得分:2)

隐藏并不意味着它不会被验证。 为什么不在局部视图中设置正确的日期/时间,而不是用空字符串初始化那些隐藏的字段。 像DateTime.Now这样的东西应该可以工作。

答案 1 :(得分:2)

鉴于您提供的模型,这是预期的行为。该模型将这两个属性指定为必需,因此隐藏的字段将添加不显眼的验证属性。