MVC4中不是必填字段

时间:2013-06-19 08:03:24

标签: asp.net-mvc-4 razor

我的剃须刀视图中是否可以没有必填字段?

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

请adivse?

@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; }

}
}

2 个答案:

答案 0 :(得分: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; 
        } 
    }
}

答案 1 :(得分:0)

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