Ответ 1
Я бы рекомендовал вам использовать модель представления и настраиваемое связующее устройство для форматов DateTime.
Начнем с определения этой модели представления:
public class MyViewModel
{
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime PreferredDate { get; set; }
}
тогда контроллер:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
PreferredDate = DateTime.Now.AddDays(2)
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// model.PreferredDate will be correctly bound here so
// that you don't need to twiddle with any FormCollection and
// removing stuff from ModelState, etc...
return View(model);
}
}
a Вид:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.PreferredDate)
@Html.EditorFor(x => x.PreferredDate)
@Html.ValidationMessageFor(x => x.PreferredDate)
<button type="submit">OK</button>
}
и, наконец, пользовательское связующее устройство для использования указанного формата:
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);
}
}
который будет зарегистрирован в Application_Start
:
ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());