在 asp.net 中使用 jQuery datepicker mvc 默认值不为空

Using jQuery datepicker in asp.net mvc default value is not null

我想使用 asp.net mvc 添加 Jquery date picker 到表单。

我得到 datepicker 但在表格中我有默认值

而且我希望日期日历是西班牙语而不是

请帮助我使用 jquery 的日期选择器。

我的代码如下

查看

@Html.EditorFor(m => m.SpanishDate, new { htmlAttributes = new { @class = "textarea", placeholder = "Spanish Date", @readonly = "true" } })
@Html.ValidationMessageFor(m => m.SpanishDate, "", new { @class = "text-danger" })

@section Scripts {

    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/cssjqryUi")

    <script type="text/javascript">
        $(document).ready(function () {
            $('input[type=datetime]').datepicker({
                dateFormat: "dd/mm/yy",
                changeMonth: true,
                changeYear: true,
                yearRange: "-2:+0"
            });
        });
    </script>
}

型号

public class PersonModel
{
    [Required]
    [Display(Name = "Spanish date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime SpanishDate { get; set; }
}

捆绑配置

//Create bundel for jQueryUI  
//js  
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(  
          "~/Scripts/jquery-ui-{version}.js"));  
//css  
bundles.Add(new StyleBundle("~/Content/cssjqryUi").Include(  
       "~/Content/jquery-ui.css")); 

更新 3 >>> 最终解决方案

新的完整部分脚本视图

@section Scripts {

    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/cssjqryUi")

    <script type="text/javascript">
        jQuery(function ($) {

            $.datepicker.regional['es'] = {
                 closeText: 'Cerrar',
                 prevText: '<Ant',
                 nextText: 'Sig>',
                 currentText: 'Hoy',
                 monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
                 monthNamesShort: ['Ene','Feb','Mar','Abr', 'May','Jun','Jul','Ago','Sep', 'Oct','Nov','Dic'],
                 dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
                 dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
                 dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sá'],
                 weekHeader: 'Sm',
                 dateFormat: 'yy-mm-dd',
                 firstDay: 1,
                 isRTL: false,
                 showMonthAfterYear: false,
                 yearSuffix: ''
            };
            $.datepicker.setDefaults($.datepicker.regional['es']);
        });

        var options = $.extend({},
            $.datepicker.regional["es"], {
            dateFormat: "mm/dd/yy",
            changeMonth: true,
            changeYear: true,
            yearRange: "-2:+0",
            highlightWeek: true,
            maxDate: 0
        }
        );
        $("# SpanishDate").datepicker(options);
    </script>
}

更新 2

完整视图

@model MVCDemo.Models.PersonModel

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Wbform</title>

    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js">
    </script>

</head>
<body>

    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        <div>
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <table cellpadding="0" cellspacing="0">
                <tr>
                    <td class="textarea">Spanish Date</td>
                    <td>

                        @Html.EditorFor(m => m.SpanishDate, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "textarea", placeholder = "Spanish Date", @readonly = "true" } })
                        @Html.ValidationMessageFor(m => m.SpanishDate, "", new { @class = "text-danger" })
                    </td>
                </tr>
            </table>
            <br />
            <hr class="new3">
            <div class="form-group">
                <div class="col-md-offset-5 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

    @section Scripts {

        @Scripts.Render("~/bundles/jqueryui")
        @Styles.Render("~/Content/cssjqryUi")

        <script type="text/javascript">

            $.datepicker.setDefaults($.datepicker.regional["es"]);
            var options = $.extend({},
                $.datepicker.regional["es"], {
                dateFormat: "mm/dd/yy",
                changeMonth: true,
                changeYear: true,
                yearRange: "-2:+0",
                highlightWeek: true, maxDate: 0
            } 
            );
            $("#SpanishDate").datepicker(options);

        </script>
    }
</body>
</html>

型号

public class PersonModel
{
    [Required]
    [Display(Name = "Spanish Date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? SpanishDate { get; set; }
}

更新

@section Scripts {

    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/cssjqryUi")

    <script type="text/javascript">
        $(document).ready(function () {
            $("#datepicker").datepicker($.datepicker.regional["es"]);
            $("#SpanishDate").datepicker({
                dateFormat: "dd/mm/yy",
                changeMonth: true,
                changeYear: true,
                yearRange: "-2:+0"
            });
        });
    </script>
}

看来您需要关注以下几项:

  1. 元素名称就是“SpanishDate”,因此您可以像下面那样使用将文本区域转换为Jquery datepicker

    $("#SpanishDate").datepicker();

  2. 您需要将值设置为您的服务器端属性 (SpanishDate) 将成为默认值

  3. 要本地化请使用以下格式

    $( "#datepicker" ).datepicker( $.datepicker.regional[ "fr" ] );

您可以在此处找到更多详细信息:https://jqueryui.com/datepicker/#default

您可以下载西班牙语本地化文件并将其包含到您的代码中

<script type="text/javascript" src="/scripts/jquery.ui.datepicker-es.js"></script>

或者使用这个 cdn:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>

日期选择器代码是:

var options = $.extend({},   
            $.datepicker.regional["es"], {  
               dateFormat: "mm/dd/yy",
              changeMonth: true,
              changeYear: true,
              yearRange: "-2:+0",
              highlightWeek: true, maxDate: 0
            } // your custom options    
        );  

        $("#SpanishDate").datepicker(options); 

您可以为 DatePickers 设置默认语言选项:

$.datepicker.setDefaults($.datepicker.regional["es"]);

并且对于 DatePicker 的空默认值,使 SpanishDate 属性 在 PersonModel 中可以为空,如下所示:

public class PersonModel
{
    [Required]
    [Display(Name = "Spanish date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? SpanishDate { get; set; }
}