berkan
berkan

Reputation: 780

MVC - Get date with textbox

I want to take two date string with textbox or editor in mvc. The format should be

"MM/yyyy-MM/yyyy".

I need to force the user for entering the input like above format without posting model.

@Html.TextBox("tbxDateRange", "", "{0:dd/MM/yyyy}", new { @class = "form-control dropdown", placeholder = "MM/yyyy - MM/yyyy" })

Above code not working event get just a formatted date string.

Upvotes: 1

Views: 755

Answers (1)

Kevin LaBranche
Kevin LaBranche

Reputation: 21078

The format is working as expected. You are telling tbxDateRange's value (the zero in the third parameter ("{0:dd/MM/yyyy}") to format as day/month/year. It will therefore take the input in the text box and display it in that format.

It is only a display format. It will not enforce this format. For that you will need to do your own client side javascript (since you mentioned without posting the model). You could look at using a masked input element. ASP.NET MVC does not have a masked input out of the box.

You could use a masked input control like maskedinput which is a plugin for jQuery.

Additionally, you might want to look at breaking this up into two controls. One for the start and one for the end. You could consider using the html5 input type of date and you will automatically get a calendar. Although, if the day of the month will be too confusing for your users/UI then you could look at using jquery UI's datepicker and you can configure it to show only month and year.

Once you include jQuery UI in your app you would do something like jQuery UI DatePicker to show month year only.

In that example the winning answer formats the control in such a way to only show the month and year items of the control.

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

Upvotes: 1

Related Questions