这可能在模型中有一个DateTime属性,但在视图/表单上使用它作为两个输入?例如,Date部分将使用jqueryui datepicker,而Time部分选择器将是一个屏蔽输入或其他漂亮的jquery插件。我不时需要使用两个投影时间(小时和分钟)。
我的目标是在模型中有一个DateTime属性(没有日期和时间的部分字符串)。这可能吗?使用MVC4。
答案 0 :(得分:2)
作为建议解决方案的替代方法,您可以使用映射到DateTime属性的隐藏字段,并在窗体上的某些控件更改日期的一部分时使用Javascript相应地在客户端修改它。
答案 1 :(得分:1)
这是我用来将日期拆分为3个字段的技术,而ViewModel上只有1个DateTime属性。虽然不完全是你所追求的,但你应该能够使用类似的方法来达到你想要的效果。
编辑模板 /views/shares/editortempaltes/datetime.cshtml
@model Nullable<System.DateTime>
@Html.TextBox("Day", Model.HasValue ? Model.Value.Day.ToString() : "", new { Type = "Number", @class="date-day" })
@Html.ValidationMessage("Day")
@Html.DropDownList("Month", months, new { @class="date-month" })
@Html.ValidationMessage("Month")
@Html.TextBox("Year", Model.HasValue ? Model.Value.Year.ToString() : "", new { Type = "Number", @class="date-year" })
@Html.ValidationMessage("Year")
自定义ModelBinder
public object GetValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
int day, month, year;
if (TryGetValue(controllerContext, bindingContext, propertyDescriptor.Name + ".Day", out day) && TryGetValue(controllerContext, bindingContext, propertyDescriptor.Name + ".Month", out month) && TryGetValue(controllerContext, bindingContext, propertyDescriptor.Name + ".Year", out year))
{
try
{
return new DateTime(year, month, day);
}
catch (ArgumentOutOfRangeException)
{
var fullPropertyName = bindingContext.ModelName + "." + propertyDescriptor.Name;
bindingContext.ModelState[fullPropertyName] = new ModelState();
bindingContext.ModelState[fullPropertyName].Errors.Add("Invalid date");
}
}
return null;
}
private bool TryGetValue(ControllerContext controllerContext, ModelBindingContext bindingContext, string propertyName, out int value)
{
var fullPropertyName = bindingContext.ModelName + "." + propertyName;
string stringValue = controllerContext.HttpContext.Request[fullPropertyName];
bindingContext.ModelState.Add(fullPropertyName, new ModelState() { Value = new ValueProviderResult(stringValue, stringValue, null) });
return int.TryParse(stringValue, out value);
}
<强>用法强> 将DateTime属性添加到ViewModel,然后调用
@Html.EditorFor(m => m.DateTimeProperty)
答案 2 :(得分:0)
是的,你可以。只需将模型传递给视图并使用DateTime,就像您尝试将值传递给字段时一样。
要获取数据,您可以返回2个DateTime(一个用于秒,一个用于时间)并组合控制器中的两个日期。
如果您需要更具体的帮助,请告诉我们您在代码中遇到问题的位置,以便我们为您提供实施帮助