Oleg Sh
Oleg Sh

Reputation: 9001

ASP.NET MVC DataAnnotation - NullTextFormat

I want to create a form, where the one field has default value, like this:

enter image description here

I created my view model class:

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

And View (by scaffolding):

    <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>

but in result no default text here:

enter image description here

why so and what I do incorrectly?

Upvotes: 0

Views: 121

Answers (1)

Abbas
Abbas

Reputation: 14432

NullDisplayText is only shown on Html.DisplayFor, not on Html.EditorFor.

You can use the placeholder attribute of the HTML element, and add it to the htmlAttributes object of the EditorFor:

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

Upvotes: 1

Related Questions