0

在我的情况下,我如何使用TextBoxFor 可空类型DateTime?

<%:Html.TextBoxFor(m => m.LeaseDate.Value.ToShortDateString(), new { @class = "def-text-input datetime-input" })%>

我试试这个,但得到错误:

异常详细信息:System.InvalidOperationException:模板只能用于字段访问、属性访问、单维数组索引或单参数自定义索引器表达式。

4

4 回答 4

1

您可以使用 Html.EditorFor

<%:Html.EditorFor(m => m.LeaseDate, "Date")%>

注意参数“日期”。这是对 EditorTemplate(通常位于“Views/Shared/EditorTemplate”文件夹中的用户控件)的引用。如果不存在,请创建用户控件/文件你自己“Date.ascx”

现在EditorFor 方法将使用这个控件作为模板。一个地方可以控制使用此模板的所有日期字段!

用户控件“Date.ascx”示例

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
    ViewDataDictionary attributes = ViewData;
    attributes.Add("class", "def-text-input datetime-input");
%>
<%= Html.TextBox(string.Empty, string.Format("{0:d-M-yyyy}", Model), attributes) %>
于 2014-02-27T13:52:38.133 回答
0

正如其他人提到的那样,您可以对模型进行格式化

[DisplayFormat(DataFormatString = "{0:MM/dd/yy}", ApplyFormatInEditMode = true)]
public DateTime LeaseDate { get; set; }

然后打电话

@Html.TextBoxFor(x => x.LeaseDate)

在你看来

但另一方面,如果您想在视图上坚持格式化,您可以使用

@Html.TextBox("LeaseDate", Model.LeaseDate.ToShortDateString())

快乐编码

于 2014-03-18T03:35:42.937 回答
-1

TextBoxFor应该用于 ViewModel 上的属性:

<%:Html.TextBoxFor(m => m.LeaseDate, new { @class = "def-text-input datetime-input" })%>

如果你想格式化你的日期,你可以在你的 ViewModel上使用DataFormatString属性上的属性:DisplayFormat

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime LeaseDate { get; set; }
于 2014-02-27T13:47:11.110 回答
-2

模型:

[DisplayFormat(DataFormatString = "{0:MM/dd/yy}", ApplyFormatInEditMode= true]
DateTime? dateAssign { get; set; }  

看法:

@Html.TextBoxFor(model => model.myObject.dateAssign)
于 2014-02-27T13:51:24.173 回答