简体   繁体   中英

Asp.net MVC web Application Date Format for Text Box

I am developing a asp.net mvc web app.

I have an issue with my partial view.

Problem is whenever i open my partial view for a "new form" i got a date in text box in following format :

在此处输入图片说明

But when i "edit record" , i get date in my partial view text box like following :

在此处输入图片说明

Following is my Model:

[DataType(DataType.Date), DisplayFormat(DataFormatString="{0:d}",ApplyFormatInEditMode=true)]
    public Nullable<System.DateTime> ReleaseDate { get; set; }

Following is my partial view code:

<div class="editor-field">
        @Html.TextBoxFor(model => model.ReleaseDate, new { @class = "Date" })
        @Html.ValidationMessageFor(model => model.ReleaseDate)
    </div>
    <script type="text/javascript">
        debugger;
        var s = $(".Date");
        s.dateFormat = "dd/mm/yyyy";
        $('.Date').datepicker({ dateFormat: "d/m/yy" });
        var newdate = Date.parse($("#ReleaseDate"));
        var rdate = $("#ReleaseDate").val();
        var fdate = Date.parse(rdate);
        debugger;
    </script>

What i want is to get the date like 16/08/2014 when i edit my record. please tell me where should i modify my code to set date format.

Thank you

You could decorate your view model property with the [DisplayFormat] attribute:

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

and in your view:

@Html.EditorFor(x => x.ReleaseDate)

Another possibility which I don't recommend is to use a weakly typed helper:

@Html.TextBox("ReleaseDate", Model.ReleaseDate.ToLongDateString())

Below is changes that you should make

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM