Rion Williams
Rion Williams

Reputation: 76557

Prepopulating masked textbox fields using MVC / jQuery

Recently I have been going through a project in an attempt to sanitize several data inputs (most are primarily Dates (mm/dd/yyyy) or DateTimes (mm/dd/yyyy hh:mm:ss am/pm).

I am using the digitalBush Masking Plugin and everything seemed to be working just as it should with empty fields. However - when I attempted to apply a masked field to a field that was bound to a ViewModel, I seemed to run into problems.

Example:

HTML:

<%= Html.TextBoxFor(model => model.DateOfBirth})%>

jQuery:

$("#DateOfBirth").mask("99/99/9999",{placeholder:" "});

I was just curious if anyone had any ideas on how to implement text-box masking on a field that was being prepopulated with data from a ViewModel, such that it would appear as usual but when it was being changed it would react as a masked input.

Upvotes: 3

Views: 10071

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038880

Instead of:

<%= Html.TextBoxFor(model => model.DateOfBirth) %>

You could write:

<%= Html.EditorFor(model => model.DateOfBirth) %>

and then you could decorate the corresponding view model property with the [DisplayFormat] attribute:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }

Upvotes: 6

Related Questions