开发者

How to use a ShortDate string format with Html.TextBoxFor

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 开发者_Python百科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


<%: 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) %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜