C# 可为空类型的TextBoxFor
在我的情况下,如何使用用户C# 可为空类型的TextBoxFor,c#,html,model-view-controller,html.textboxfor,htmlextensions,C#,Html,Model View Controller,Html.textboxfor,Htmlextensions,在我的情况下,如何使用用户TextBoxFor获取可空类型的DateTime? <%:Html.TextBoxFor(m => m.LeaseDate.Value.ToShortDateString(), new { @class = "def-text-input datetime-input" })%> m.LeaseDate.Value.toSortDateString(),新的{@class=“def text input datetime input”})%%>
TextBoxFor
获取可空类型的DateTime?
<%:Html.TextBoxFor(m => m.LeaseDate.Value.ToShortDateString(), new { @class = "def-text-input datetime-input" })%>
m.LeaseDate.Value.toSortDateString(),新的{@class=“def text input datetime input”})%%>
我尝试此操作,但出现错误:
异常详细信息:System.InvalidOperationException:模板可以是
仅用于字段访问、属性访问、一维数组
索引,或单参数自定义索引器表达式
TextBoxFor
应用于ViewModel上的属性:
<%:Html.TextBoxFor(m => m.LeaseDate, new { @class = "def-text-input datetime-input" })%>
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime LeaseDate { get; set; }
型号:
视图:
您可以使用Html.EditorFor
<%:Html.EditorFor(m => m.LeaseDate, "Date")%>
m.LeaseDate,“Date”)%>
请注意参数“日期”。这是对EditorTemplate的引用(usercontrol通常位于“Views/Shared/EditorTemplate”文件夹中)。如果不存在,请创建用户控件/文件“Date.ascx”
现在EditorFor方法将使用此控件作为模板。一个地方可以控制所有使用此模板的日期字段
UserControl“Date.ascx”的示例
正如其他人提到的,您可以在模型上进行格式化
[DisplayFormat(DataFormatString = "{0:MM/dd/yy}", ApplyFormatInEditMode = true)]
public DateTime LeaseDate { get; set; }
然后打电话
@Html.TextBoxFor(x => x.LeaseDate)
在你看来
但另一方面,如果您想坚持在视图上设置格式,可以使用
@Html.TextBox("LeaseDate", Model.LeaseDate.ToShortDateString())
快乐编码这是什么类型的页面可能重复?如果它是一个创建页面,您可以简单地在输入的同时使用jQuery UI的日期选择器,它会自动将日期格式化为一个短日期。不知道为什么,但不知道为什么,但是它没有帮助。如果您使用的是
Html.EditorFor
而不是Html.TextBoxFor
,怎么样?我想跳过这个解决方案,我相信还有更简单的解决方案
[DisplayFormat(DataFormatString = "{0:MM/dd/yy}", ApplyFormatInEditMode = true)]
public DateTime LeaseDate { get; set; }
@Html.TextBoxFor(x => x.LeaseDate)
@Html.TextBox("LeaseDate", Model.LeaseDate.ToShortDateString())