0

TextBoxFor 私の場合、null許容型を使用するにはどうすればよいですか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 メソッドはこのコントロールをテンプレートとして使用します。このテンプレートを使用するすべての日付フィールドを 1 か所で管理できます。

UserControl「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

TextBoxForViewModel のプロパティに使用する必要があります。

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

日付をフォーマットする場合は、ViewModelDataFormatStringの属性でプロパティを使用できます。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 に答える