【问题标题】:ASP.NET MVC DataAnnotation - NullTextFormatASP.NET MVC DataAnnotation - NullTextFormat
【发布时间】:2023-03-09 15:33:01
【问题描述】:

我想创建一个表单,其中一个字段具有默认值,如下所示:

我创建了我的视图模型类:

public class ApplicationDriverLicenseVM
{
    [Required]
    [Display(Name = "CDL Expiration Date")]
    [DisplayFormat(ConvertEmptyStringToNull = true, NullDisplayText = "MM/DD/YYYY")]
    public DateTime? CDLExpDate { get; set; }

和视图(通过脚手架):

    <div class="form-group">
        @Html.LabelFor(model => model.CDLExpDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CDLExpDate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CDLExpDate, "", new { @class = "text-danger" })
        </div>
    </div>

但结果这里没有默认文本:

为什么会这样,我做错了什么?

【问题讨论】:

  • 我相信您可能正在寻找占位符。 new { htmlAttributes = new { @class = "form-control", placeholder = "MM/DD/YYYY" }
  • NullDisplayText 仅在您使用 @Html.DisplayFor() 时才会受到尊重

标签: asp.net-mvc data-annotations


【解决方案1】:

NullDisplayText 仅显示在 Html.DisplayFor 上,而不显示在 Html.EditorFor 上。

您可以使用HTML元素的placeholder属性,并将其添加到EditorFor的htmlAttributes对象中:

@Html.EditorFor(model => model.CDLExpDate, new { 
        htmlAttributes = new { 
            @class = "form-control",
            @placeholder = "MM/DD/YYYY" 
        }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-02
    • 2023-04-07
    • 2013-01-15
    • 2015-05-02
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2022-07-21
    相关资源
    最近更新 更多