gpt4 book ai didi

c# - 如何在 Html.TextBoxFor 中使用 ShortDate 字符串格式

转载 作者:太空狗 更新时间:2023-10-30 00:02:13 24 4
gpt4 key购买 nike

将 Entity Framework 与 MVC2 结合使用,我有一系列日期文本框,我想以短日期格式显示模型中的数据,但我必须使用 Html.TextBoxFor 才能使更新代码正常工作(具有尝试使用 HTML.Textbox 数据永远不会保存到模型中)。

<%: Html.TextBoxFor(model => model.Item.Date, String.Format("{0:d}", Model.Item.Date))%>

我已经尝试操纵字符串格式表达式,并将元数据添加到映射到 Entity Framework 模型类的部分类中,但是我仍然在表单渲染时得到以下填充文本框的信息:

01/01/2011 00:00:00 

而不是

01/01/2011

最佳答案

<%: Html.EditorFor(model => model.Item.Date) %>

在您的 View 模型上:

[DataType(DataType.Time)]  
[DisplayFormatAttribute(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime Date { get; set; }

更新:

完整示例:

型号:

public class MyModel
{
public Item Item { get; set; }
}

public class Item
{
[DataType(DataType.Time)]
[DisplayFormatAttribute(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime Date { get; set; }
}

Controller :

public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyModel
{
Item = new Item { Date = DateTime.Now }
});
}
}

查看:

<%: Html.EditorFor(model => model.Item.Date) %>

关于c# - 如何在 Html.TextBoxFor 中使用 ShortDate 字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3758573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com