jQuery.ui.DatePicker con ASP.NET MVC DateFormat Mapping
-
19-09-2019 - |
Domanda
C'è da qualche parte qualcuno che ha fatto una mappatura del C# DateFormat al DatePicker DateFormat, dal momento che conosco già C# DateFormat, non voglio dover controllare la documentazione DatePicker ogni volta che devo costruire un formato di data personalizzato.
Per exmple, voglio essere in grado di specificare nel mio helper dataformat di "dd/mm /y" (c#) e lo convertirebbe in datepicker "dd/mm/yy"
Soluzione
Un possibile approccio sarebbe quello di sostituire direttamente gli specificatori del formato .NET con le loro controparti jQuery come puoi vedere nel seguente codice:
public static string ConvertDateFormat(string format)
{
string currentFormat = format;
// Convert the date
currentFormat = currentFormat.Replace("dddd", "DD");
currentFormat = currentFormat.Replace("ddd", "D");
// Convert month
if (currentFormat.Contains("MMMM"))
{
currentFormat = currentFormat.Replace("MMMM", "MM");
}
else if (currentFormat.Contains("MMM"))
{
currentFormat = currentFormat.Replace("MMM", "M");
}
else if (currentFormat.Contains("MM"))
{
currentFormat = currentFormat.Replace("MM", "mm");
}
else
{
currentFormat = currentFormat.Replace("M", "m");
}
// Convert year
currentFormat = currentFormat.Contains("yyyy") ? currentFormat.Replace("yyyy", "yy") : currentFormat.Replace("yy", "y");
return currentFormat;
}
Fonte originale: http://rajeeshcv.com/2010/02/28/jqueryui-datepicker-in-asp-net-mvc/
Altri suggerimenti
Forse puoi usare qualcosa di simile:
<%= Html.TextBoxFor(x => x.SomeDate, new { @class = "datebox", dateformat = "dd/mm/yy" })%>
e questo:
$(function() {
$("input.datebox").each(function() {
$(this).datepicker({ dateFormat: $(this).attr("dateFormat") });
});
});