[英]ASP.NET MVC EditorFor and DateTime default value
我想為EditorFor HTML幫助程序設置默認值,但其中僅顯示幫助程序文本。 為什么EditorFor不允許我設置其默認值?
class Person {
public int Id { get; set; }
public DateTime DateOfBirth { get; set; }
...
}
class PersonVM {
public Person { get; set; }
...
}
public ActionResult Edit(int id)
{
var vm = new PersonVM ();
vm.Person = db.Persons.Where(x => x.Id == id).FirstOrDefault();
...
return View(vm);
}
@model Project.Models.PersonVM
@Html.EditorFor(model => model.Person.DateOfBirth , new { htmlAttributes = new { @class = "form-control" } })
通過為模型屬性分配值來設置默認值。
在控制器動作中:
public ActionResult Edit(int id) {
var vm = new PersonVM ();
vm.Person = db.Persons.Where(x => x.Id == id).FirstOrDefault();
if (vm.Person.DateOfBirth == default(DateTime)) {
vm.Person.DateOfBirth = new DateTime(1900, 01, 01); // default value
}
// ...
return View(vm);
}
或在ViewModel中(確保僅將有效的DateOfBirth從數據庫映射到ViewModel):
public class PersonVM {
public PersonViewModel () {
DateOfBirth = new DateTime(1900, 01, 01); // default value
}
public int Id { get; set; }
public DateTime DateOfBirth { get; set; }
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.