【问题标题】:TextBoxFor for Nullable type可空类型的 TextBoxFor
【发布时间】:2014-02-27 13:40:24
【问题描述】:

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

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

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

异常详细信息:System.InvalidOperationException:模板可以 仅与字段访问、属性访问、一维数组一起使用 index 或单参数自定义索引器表达式。

【问题讨论】:

  • 这是什么类型的页面?如果是创建页面,您可以简单地使用 jQuery UI 的日期选择器与输入一起自动将日期格式化为短日期。

标签: c# html model-view-controller html.textboxfor htmlextensions


【解决方案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) %>

【讨论】:

  • 我想还有更简单的解决方案
【解决方案2】:

正如其他人所说,您可以对模型进行格式化

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

然后调用

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

在你看来

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

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

快乐编码

【讨论】:

    【解决方案3】:

    TextBoxFor 应该用于 ViewModel 上的属性:

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

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

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

    【讨论】:

    • 不知道为什么,但它没有帮助。
    • 如果你使用Html.EditorFor而不是Html.TextBoxFor怎么样?
    • 我想跳过这个解决方案
    【解决方案4】:

    型号:

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

    查看:

    @Html.TextBoxFor(model => model.myObject.dateAssign)
    

    【讨论】:

    • 不知道为什么,但它没有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 2021-02-17
    相关资源
    最近更新 更多