Sue*_* Su 9 c# asp.net-mvc model string-formatting data-annotations
我想在Controller中为我的模型设置一个默认值,但它无法在创建页面中显示.
TestModel代码:
public class TestModel
{
[DataType(DataType.DateTime), Required]
[DisplayFormat(DataFormatString = "yyyy/MM/dd", ApplyFormatInEditMode = true)]
public DateTime StartTime { get; set; }
[DataType(DataType.DateTime), Required]
[DisplayFormat(DataFormatString = "yyyy/MM/dd", ApplyFormatInEditMode = true)]
public DateTime EndTime { get; set; }
public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器代码:
public ActionResult Create()
{
var model = new TestModel();
model.StartTime = DateTime.Now;
model.EndTime = DateTime.Now.AddDays(10);
model.Description = "This is a default value";
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
查看页面:
<div class="form-group">
@Html.LabelFor(model => model.StartTime, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StartTime)
@Html.ValidationMessageFor(model => model.StartTime)
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
您需要具有如下所示的模型类属性:
[DataType(DataType.Date), Required]
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime StartTime { get; set; }
[DataType(DataType.Date), Required]
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime EndTime { get; set; }
Run Code Online (Sandbox Code Playgroud)
当您使用中[DataType(DataType.Date)]的默认模板装饰模型属性时,将ASP.NET MVC生成输入字段type="date"。
| 归档时间: |
|
| 查看次数: |
9292 次 |
| 最近记录: |