簡體   English   中英

我嘗試這樣做時出現模板錯誤?

[英]Get a template error when I try to do this?

我正在使用asp.net mvc 3並且我一直收到此錯誤,因為我沒有使用模板,所以我不理解它。

我在局部視野中有這個

@model ViewModels.FormViewModel

    <div="tabs-1">
        @Html.TextBoxFor(x => x.Due.ToShortDateString())
    </div>

在我的viewmodel中

public class FormViewModel
    {
        public DateTime Due { get; set; }


        public FormViewModel()
        {
            DueDate = DateTime.UtcNow;         
        }
    }

我收到這個錯誤

模板只能用於字段訪問,屬性訪問,單維數組索引或單參數自定義索引器表達式。 描述:執行當前Web請求期間發生未處理的異常。 請查看堆棧跟蹤以獲取有關錯誤及其源自代碼的位置的更多信息。

異常詳細信息:System.InvalidOperationException:模板只能用於字段訪問,屬性訪問,單維數組索引或單參數自定義索引器表達式。

應該是這樣的:

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

如果你想要這個日期的格式:

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

然后:

@Html.EditorFor(x => x.Due)

如果你真的想使用這個.ToShortDateString()方法,你需要使用非強類型的幫助器(顯然這是我建議反對的):

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

有一個重載可以幫助實現這一點,同時保持強類型。

// Specify that you're providing the format argument (string)
@Html.TextBoxFor(x => x.Due, format: Model.Due.ToShortDateString())

// Or use the overload with format and html options, where null is the htmloptions
@Html.TextBoxFor(x => x.Due, Model.Due.ToShortDateString(), null)

如果您使用MVC並具有內聯代碼元素,請嘗試設置如下參數 -

@{
string parameterValue = DateTime.Parse(@item.Value).ToShortDateString();

}

@Html.DisplayFor(model => parameterValue)

你得到的錯誤是因為.TextBoxFor() html助手正在使用一個內置模板(一個用於字符串輸入的文本框),並且你給它一個太復雜的lambda表達式(即不屬於該集合)消息中列出的類型)。

要解決此問題,請將要編輯的屬性的類型更改為string ,以便MVC可以使用默認的字符串模板,或者讓MVC使用默認的日期時間模板。 我推薦后者:

@Html.TextBoxFor(m => m.Due)

如果您對用戶被要求編輯日期的方式不滿意,請在〜/ Views / Shared / EditorTemplates中放置一個名為“DateTime.cshtml”的部分視圖,您可以在其中構建編輯器,使其按您希望的方式工作。

您通過在textboxfor的參數中傳遞方法而不是傳遞表達式來誤導應用程序。

你有過 :

@Html.TextBoxFor(x => x.Due.ToShortDateString())

將結果存儲在變量中,然后使用表達式。 試試這個

var shortDate = Model.Due.ToShortDateString();
@Html.TextBoxFor(x => shortDate )

而不是在模型中添加格式使用@Value Annotations如下所示

@ Html.TextBoxFor(x => x.Due new {@ Value = Model.Due.ToShortDateString()})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM