【问题标题】:MVC3 Navigation Property Attributes and Client Side ValidationMVC3 导航属性属性和客户端验证
【发布时间】:2012-05-02 08:54:55
【问题描述】:

我正在尝试进入 MVC3 并遇到了将模型中的导航属性转换为视图的问题。似乎在视图中导航属性不允许客户端验证,也没有选择“显示”标签属性。

我有以下简单模型:

public class Entity
{
    [Key,
    ScaffoldColumn(false)]
    public int Entity_Id { get; set; }

    [Display(Name = "Entity Name"),
    Required(ErrorMessage = "Please enter the entity name."),
    StringLength(150, ErrorMessage = "Please ensure that the entity name is under 150 characters.")]
    public string Entity_Nm { get; set; }

    [Display(Name = "Entity Type"), 
    Required(ErrorMessage="Please select the entity type"),
    ForeignKey("EntityType")]
    public int EntityType_Id { get; set; }

    public virtual EntityType EntityType { get; set; }
}

引用此模型:

public class EntityType
{
    [Key]
    public int EntityType_Id { get; set; }

    [Display(Name = "Entity Name"), Required(ErrorMessage="Please enter the entity type name.")]
    public string EntityType_Nm { get; set; }
}

当我为此模型创建具有读/写操作和视图的控制器时,我得到以下创建表单:

<fieldset>
    <legend>Entity</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Entity_Nm)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Entity_Nm)
        @Html.ValidationMessageFor(model => model.Entity_Nm)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.EntityType_Id, "EntityType")
    </div>
    <div class="editor-field">
        @Html.DropDownList("EntityType_Id", String.Empty)
        @Html.ValidationMessageFor(model => model.EntityType_Id)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

除了实体类型下拉列表的标签之外,这很好,由于某种原因,它没有选择模型内导航属性的“显示”属性(注意缺少空格)。尽管使用“必需”属性装饰了属性,但也没有为下拉列表启用客户端验证(服务器端验证没有问题)。客户端验证适用于其他字段。请注意,所有必需的 .js 脚本文件都已包含在内,并且我还在 web.config 中添加了相关的启用验证密钥。

任何想法我在这里缺少什么?谢谢大家。

【问题讨论】:

    标签: asp.net-mvc-3 attributes validation navigation-properties


    【解决方案1】:

    对于 DropDownList 显示问题,请在下面尝试

    @Html.LabelFor(model => model.EntityType_Id)

    【讨论】:

    • 谢谢swapneel 我已经用它来解决标签问题,问题是为什么表单是使用附加参数生成的?这意味着如果表单再次自动生成,我将需要记住更改。
    猜你喜欢
    • 2012-03-06
    • 2011-08-05
    • 2011-10-11
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    相关资源
    最近更新 更多