输入与视图模型日期格式设置和HTML类属性 [英] Input with date format set from ViewModel and html class attribute
问题描述
我用剃刀视图引擎在asp.net MVC3工作。
I am working with razor view engine in asp.net mvc3.
现在,我需要一个的DateTime
这应该显示在一个固定的格式(价值比如说 DD-MMM-YYYY $输入C $ C>)。因此,我可以做的:
Now, I need an input for a DateTime
which should display the value in a fixed format (say dd-MMM-yyyy
). So I can do:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yyyy}")]
public DateTime StartDate { get; set; }
和视图:
@Html.EditorFor(model => model.StartDate)
但我需要在输入添加一个类。我认为这是不可能的 EditorFor
。
所以,我可以使用
But I need to add a class in the input. Which I think is not possible in EditorFor
.
So I could use
@Html.TextBoxFor(model => model.StartDate, new { @class = "Date" })
但显示格式不在此情况下工作。
But the display format does not work in this case.
模式
可以为null。因此,
Model
can be null. So,
@Html.TextBox("StartDate", string.Format("{0:dd-MMM-yyyy}", Model.StartDate))
将抛出的NullReferenceException
。
推荐答案
绿萍的方式是我的一个更快的版本。但是,如果你要在你的应用程序中的几个日期字段这种方式是非常有用的。所以这是我喜欢做的方式:
ophelia's way is a quicker version of mine. But this way is useful if you're going to have a few date fields in your application. So this is the way i like to do it:
- >在解决方案资源管理器后,创建一个文件夹的在的共享名为 EditorTemplates
-> In your solution explorer, create a folder inside Shared called "EditorTemplates"
- >在那里,添加一个新的(不可以强类型)的局部视图即可。称它为的DateTime
。
-> In there, add a new (not strongly typed) Partial View. Call it "DateTime
".
- >打开这个观点,并移除任何code在那里,并引发以下code在那里:
-> Open this view, and remove any code in there, and throw the following code in there:
@model System.DateTime
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date" /* + any other html attributes you want */ })
- >在视图模型,您的日期字段应该是这样的:
-> In your ViewModel, your date field should be like this:
[Display(Name = "My Date:"), DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime MyDate { get; set; }
- >在主视图,然后你要使用日期字段,你可以使用 EditorFor
对财产的任何观点,像这样:
-> In your main view, and any view you want to use a date field, you can just use EditorFor
on the property, like so:
@Html.EditorFor(m => m.MyDate)
您可以在您的控制器初始化日期字段或设置您的视图模型的构造一个默认的日期。
You can initialize the date field in your controller or set a default date in your viewmodel's constructor.
这篇关于输入与视图模型日期格式设置和HTML类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!