Skip to content

Instantly share code, notes, and snippets.

@nzhul
Last active August 29, 2015 14:26
Show Gist options
  • Save nzhul/a2aa619ed87829ebec0a to your computer and use it in GitHub Desktop.
Save nzhul/a2aa619ed87829ebec0a to your computer and use it in GitHub Desktop.
--------------------------- THE MODEL --------------------------------------
public class DatePickerInputModel
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
}
------------------------------ APP START CONFIGURATION ----------------
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder()); // <---------- !!!!
}
----------------------------------------
public class MyDateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
------------------ THE VIEW -----------------------------
@model DatePicker.Controllers.DatePickerInputModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div style="margin: 0 auto; width: 500px;position:relative; top:250px;">
@using (Html.BeginForm("SendData", "Home", FormMethod.Post, new { @class = "someclass" }))
{
@Html.TextBoxFor(model => model.Date, new { @class = "datepicker", placeholder = "Enter Drop-off date here..." })
<input type="submit" name="name" value="submit" />
}
</div>
<script>
$(function () {
$('.datepicker').datepicker({
format: 'dd-mm-yyyy'
});
});
</script>
------------------ web.config GLOBALIZATION ---------------------
You need to set the proper culture in the globalization element of your web.config file for which dd.MM.yyyy is a valid datetime format:
<globalization culture="...." uiCulture="...." />
For example that's the default format in german: de-DE.
// This is for format dd-mm-yyyy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment