简体   繁体   中英

ASP .NET MVC4 Datepicker with month and year only

I'm trying to make a datepicker which will display years and month only.

I saw this questions in different places but all the solutions I have tested doesn't work.

I follow this example : http://jsfiddle.net/bopperben/DBpJe/

Here is my .cshtml file :

@using Site.Models
@{
    ViewBag.Title = "Rapports";
}

<script type="text/javascript">
    $(function() {
    $('.date-picker').datepicker( {
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'MM yy',
    onClose: function(dateText, inst) { 
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));
    }
    });
    });
</script>
<style type="text/css">
    .ui-datepicker-calendar {
    display: none;
    }
</style>

<h2>Rapports</h2>

<div>

    @using (Html.BeginForm()) {
        <input name="startDate" id="startDate" class="date-picker" />
        <input type="submit" value="Rechercher" />
    } 

</div>

But in my page there is only a textbox and nothing pop up when I click it. I don't know what I am doing wrong.

Did you start from an ASP.NET MVC4 internet template?

I've tried your code above and got it working on two details.

I added the script tag in a section scripts (that will make sure it renders after jquery is loaded)

@section scripts
{
    <script type="text/javascript">
        $(document).ready(function() {
            $('.date-picker').datepicker({
                changeMonth: true,
                changeYear: true,
                showButtonPanel: true,
                dateFormat: 'MM yy',
                onClose: function(dateText, inst) {
                    var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                    var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                    $(this).datepicker('setDate', new Date(year, month, 1));
                }
            });
        });
    </script>
}

In the _Layout.cshtml I've added the jquerui bundle (script and style) (loads jqueryui in the page)

//In head tag
@Styles.Render("~/Content/css")
@Styles.Render("~/Content/themes/base/css")

//After closing footer tag

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")

@RenderSection("scripts", required: false)

屏幕截图

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