【问题标题】:Unobtrusive validation problem with DropDownListFor in ASP.NET MVC 3ASP.NET MVC 3 中 DropDownListFor 的不显眼验证问题
【发布时间】:2011-06-28 00:24:36
【问题描述】:

即使我没有在我的模型中指定 [Required] 属性,为什么会触发客户端验证说我的默认主题字段是必需的?

型号:

public class Site
{
    public int SiteId { get; set; }

    [Required(ErrorMessage = "*")]
    [LocalizedDisplayName("Title")]
    public string Title { get; set; }

    [Required(ErrorMessage = "*")]
    [LocalizedDisplayName("RootDirectory")]
    public string RootDirectory { get; set; }

    [LocalizedDisplayName("DefaultTheme")]
    public int DefaultThemeId { get; set; } // <-- No required attribute here

    [Required(ErrorMessage = "*")]
    [LocalizedDisplayName("ThemesDirectory")]
    public string ThemesDirectory { get; set; }

    public virtual Theme DefaultTheme { get; set; } // <-- No required attribute here
}

查看:

@Html.DropDownListFor(x => x.DefaultThemeId,
new SelectList(ViewBag.Themes, "ThemeId", "Name"), string.Empty)

我正在使用带有 ADO.NET 实体数据模型的 Entity Framework 4,并将实体映射到我的模型中的 POCO。

【问题讨论】:

    标签: asp.net asp.net-mvc entity-framework-4 asp.net-mvc-3 unobtrusive-validation


    【解决方案1】:

    这是因为 int 具有隐式值。如果您希望它没有值,请使用 int 将类型更改为可为空的 int?

    【讨论】:

    • 如果您真的想将其保留为 int,您可以在 Global.asax 中将 DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes 设置为 false 我建议使用 int?但是。
    • 谢谢@Nigel。一整天都在搜索!
    猜你喜欢
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2011-12-22
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多