How to use a ShortDate string format with Html.TextBoxFor

我怕爱的太早我们不能终老 提交于 2019-12-07 09:05:41

问题


Using Entity Framework with MVC2, I have a series of date textboxes, that I want to display data from the model in a short date format, but I have to use Html.TextBoxFor in order for the update code to work (Having tried using HTML.Textbox the data never gets saved to the model).

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

I've tried manipulating the string format expression, and have added metadata to a partial class mapped to the Entity Framework model class, however still I get the following populating my textboxes at form render:

01/01/2011 00:00:00 

rather than

01/01/2011

回答1:


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

And on your view model:

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

UPDATE:

Full example:

Model:

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 }
        });
    }
}

View:

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


来源:https://stackoverflow.com/questions/3758573/how-to-use-a-shortdate-string-format-with-html-textboxfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!