开发者

Prepopulating masked textbox fields using MVC / jQuery

开发者 https://www.devze.com 2023-02-19 05:36 出处:网络
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).

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开发者_StackOverflow中文版 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.


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; }
0

精彩评论

暂无评论...
验证码 换一张
取 消