0

我可以在我的剃刀视图中没有必填字段吗?

我有以下视图,其中我希望隐藏字段不是必填字段。目前它被视为强制性的,我的模型状态是错误的。

请注意?

@using P.M.O
@model O

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Create a New O</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.C) 
        @Html.TextBoxFor(model => model.C, new { @class = "txt"}) 
        @Html.ValidationMessageFor(model => model.Caption) 
    </div> <br />

    <div class="editor-label">
        @Html.LabelFor(model => model.N)
        @Html.TextBoxFor(model => model.N, new { @class = "txt"}) 
        @Html.ValidationMessageFor(model => model.N)
    </div> <br />

    <div class="editor-label">
        @Html.LabelFor(model => model.D)
        @Html.TextBoxFor(model => model.D, new { @class = "txt"}) 
        @Html.ValidationMessageFor(model => model.D)
    </div> 
    <br />
        @Html.HiddenFor(model=> model.P.Cr)
        <input type="submit" value="Create" />
</fieldset>
}  

模型:

 using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace P.M.O
{
[Serializable]
public partial class O
{
    /*** Construtor(s) ***/
    public O()
    {

    }

    public O(P obj)
        : this()
    {
        P= obj;
    }


    /*** Public Members ***/
    [Key, Display(Name = "Id")]
    public int PartyId { get; set; }


    /* IEntity */
    public string C{ get; set; }

    public string N{ get; set; }

    public string D{ get; set; }


    /* IAuditable */
    [NotMapped, ScaffoldColumn(false)]
    public System.DateTimeOffset Created
    {
        get { return P.C; }
        set { P.C= value; }
    }

    /* Navigation Properties */
    /// <summary>
    /// Foreign key to Party: PartyId
    /// Organization is subtype of  Party
    /// </summary>
    public virtual P P{ get; set; }

}
}
4

2 回答 2

3

您应该将您的Created属性定义为可为空的DateTimeOffset

/* IAuditable */
[NotMapped, ScaffoldColumn(false)]
public System.DateTimeOffset? Created
{
    get { return Party.Created; }
    set { Party.Created = value; }
}

编辑:并考虑到该Party属性可能是null

public System.DateTimeOffset? Created
{
    get 
    { 
        return Party == null ? null : Party.Created; 
    }
    set 
    { 
        if (Party == null) 
        {
            return; 
        } 
        else 
        { 
            Party.Created = value; 
        } 
    }
}
于 2013-06-19T08:11:52.447 回答
0

使用自定义模型绑定器创建子对象或父对象。模型绑定器解决了这个问题。

于 2013-07-08T09:49:04.817 回答