.net 用于 mvc3 日期格式和日期验证的文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5033902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:16:59  来源:igfitidea点击:

Textboxfor mvc3 date formatting and date validation

.netasp.net-mvcasp.net-mvc-3

提问by LanFeusT

I've decided to get started with MVC 3 and I ran into this issue while trying to redo one of my web apps to MVC3.

我决定开始使用 MVC 3 并且在尝试将我的一个 Web 应用程序重做到 MVC3 时遇到了这个问题。

I've got projects setup this way:

我有这样的项目设置:

public class Project
{
    public int      ProjectID       { get; set; }

    [Required(ErrorMessage="A name is required")]
    public string   Name            { get; set; }

    [DisplayName("Team")]
    [Required(ErrorMessage="A team is required")]
    public int      TeamId          { get; set; }

    [DisplayName("Start Date")]
    [Required(ErrorMessage="A Start Date is required")]
    [DisplayFormat(ApplyFormatInEditMode=true, DataFormatString="{0:d}")]
    public DateTime StartDate       { get; set; }

    [DisplayName("End Date")]
    [Required(ErrorMessage="An End Date is required")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
    public DateTime EndDate         { get; set; }
}

And my entry form is written this way for the dates:

我的报名表是这样写的:

<table>
    <tr>
        <td>
            <div class="editor-label">
                @Html.LabelFor(model => model.StartDate)
            </div>
        </td>
        <td>
            <div class="editor-label">
                @Html.LabelFor(model => model.EndDate)
            </div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.StartDate, new { @class = "datepicker", id="txtStartDate" })
                @Html.ValidationMessageFor(model => model.StartDate)
            </div>
        </td>
        <td>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.EndDate, new { @class = "datepicker", id = "txtEndDate" })
                @Html.ValidationMessageFor(model => model.EndDate)
            </div>
        </td>
    </tr>
</table>

My problem is that the textbox are now displaying 01/Jan/0001 00:00:00. So first: how can I get the date to be formated to shortdatestring? I've found an MVC2 solutionwhich advised to create an EditorTemplates folder in the SharedFolder and use EditorFor instead but that did not seem to be working with MVC3 . It also seemed to prevent adding classes easily like it is with TextBoxFor

我的问题是文本框现在显示 01/Jan/0001 00:00:00。首先:如何将日期格式化为短日期字符串?我找到了一个MVC2 解决方案,它建议在 SharedFolder 中创建一个 EditorTemplates 文件夹并改用 EditorFor ,但这似乎不适用于 MVC3 。它似乎也阻止了像 TextBoxFor 那样轻松添加类

And secondly once that is fixed I've got a special validation system that I need to put in place. I need to have the End Date to be AFTER the Start Date. I'm thinking of doing the check with a javascript i found http://www.datejs.combut is there a way to do the validation directly on my class?

其次,一旦解决了这个问题,我就有了一个需要安装到位的特殊验证系统。我需要将结束日期晚于开始日期。我正在考虑使用我在http://www.datejs.com 上找到的 javascript 进行检查,但是有没有办法直接在我的班级上进行验证?

采纳答案by DarkStar33

For your edit template try this

对于您的编辑模板,试试这个

@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" })

Source: MVC 3 Editor Template with DateTime

来源:MVC 3 Editor Template with DateTime

jQuery DateTime comparisons

jQuery 日期时间比较

$('#txtbox').change(function() {
            var date = $(this).val();
            var arrDate = date.split("/");
            var today = new Date();
            useDate = new Date(arrDate[2], arrDate[1] -1, arrDate[0]);

            if (useDate > today) {
                alert('Please Enter the correctDate');
                $(this).val('');
            }
        });

Source: Jquery date comparison

来源:Jquery 日期比较

回答by Liam

there is a considerably easier way of doing this. Just use a TextBoxrather than a TextBoxFor

有一种相当简单的方法可以做到这一点。只需使用 aTextBox而不是 aTextBoxFor

@Html.TextBox("ReturnDepartureDate", 
    Model.ReturnDepartureDate.ToString("dd/MM/yyyy"))

this has the advantage of adding all the unobtrusive JavaScript elements, etc. Also less code!

这具有添加所有不显眼的 JavaScript 元素等的优点。代码也更少!

回答by Irfons

Have a look at this example

看看这个例子

@Html.TextBoxFor(s => s.dateofbirth, new { Value = @Model.dateofbirth.ToString("dd/MM/yyyy") })

回答by Craig B

If you decorate your viewmodel object with the following you'll only see the date portion within the text box.

如果您使用以下内容装饰您的 viewmodel 对象,您将只会在文本框中看到日期部分。

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime Date { get; set; }

Then on your page you can simply do the following

然后在您的页面上,您只需执行以下操作

@Html.EditorFor(model => model.Date)

Note that this is using standard MVC3. I don't have a custom Date editor template.

请注意,这是使用标准 MVC3。我没有自定义日期编辑器模板。

All credit for this answer goes to assign date format with data annotations

此答案的所有功劳都用于分配带有数据注释的日期格式

回答by coymax

// datimetime displays in the datePicker is 11/24/2011 12:00:00 AM

// datePicker 中显示的日期时间是 11/24/2011 12:00:00 AM

// you could split this by space and set the value to date only

// 您可以将其按空间拆分并将值设置为仅日期

Script:

脚本:

    if ($("#StartDate").val() != '') {
        var arrDate = $('#StartDate').val().split(" ");
        $('#StartDate').val(arrDate[0]);
    }

Markup:

标记:

    <div class="editor-field">
        @Html.LabelFor(model => model.StartDate, "Start Date")
        @Html.TextBoxFor(model => model.StartDate, new { @class = "date-picker-needed" })
    </div>

Hopes this helps..

希望这有帮助..

回答by Ali Adravi

Too late but might be it can help to someone:

为时已晚,但可能对某人有所帮助:

Model:

模型:

[Display(Name = "Date of birth")]
public DateTime? DOB{ get; set; }

HTML:

HTML:

@Html.TextBoxFor(m => m.DOB, "{0:MM/dd/yyyy}", 
          new { @placeholder="MM/DD/YYYY", @au19tocomplete="off" }) 

JavaScript to add the calendar to the control:

将日历添加到控件的 JavaScript:

$('#DOB').datepicker({changeMonth: true, changeYear: true, 
         minDate: '01/01/1900',  maxDate: new Date});