3 回答

TA貢獻2080條經驗 獲得超4個贊
啊,現在很清楚。您似乎在綁定值時遇到問題。不能在視圖上顯示它。確實,這是默認模型綁定程序的錯誤。您可以編寫并使用一種定制[DisplayFormat]模型,該模型將考慮模型上的屬性。我已經在這里說明了這樣的自定義模型活頁夾:https : //stackoverflow.com/a/7836093/29407
顯然,一些問題仍然存在。這是我的完整設置,可以在ASP.NET MVC 3和4 RC上正常運行。
模型:
public class MyViewModel
{
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
視圖:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.Birth)
@Html.EditorFor(x => x.Birth)
@Html.ValidationMessageFor(x => x.Birth)
<button type="submit">OK</button>
}
在以下位置注冊自定義模型活頁夾Application_Start:
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);
}
}
現在,無論您在web.config(<globalization>元素)中設置了哪種區域性還是當前的線程區域性,自定義模型綁定程序DisplayFormat在解析可為空的日期時都將使用屬性的日期格式。
- 3 回答
- 0 關注
- 752 瀏覽
添加回答
舉報