簡體   English   中英

為字符串屬性 ASP.NET MVC4 創建 EditorTemplate

[英]Creating EditorTemplate for string properties ASP.NET MVC4

當我在表單中使用 Html.EditorFor 助手時,我希望能夠自定義標簽的外觀,因此我定義了一個 EditorTemplate 來做到這一點。 這就是我的表單在我看來的樣子:

 @model Models.SimpleUserClass @{ ViewBag.Title = "Create User"; } <div class="row"> <div class="col-lg-6" id="FromPlaceHoler"> @using (Html.BeginForm("CreateUser", "Users")) { <fieldset> <legend>Create One Way Trip</legend> <div class="editor-label"> @Html.LabelFor(model => model.UserName) </div> <div class="editor-field"> @Html.EditorFor(model => model.UserName) </div> <div class="editor-label"> @Html.LabelFor(model => model.UserSurname) </div> <div class="editor-field"> @Html.EditorFor(model => model.UserSurname) </div> <div class="editor-label"> @Html.LabelFor(model => model.UserAge) </div> <div class="editor-field"> @Html.EditorFor(model => model.UserAge) </div> <div class="editor-label"> @Html.LabelFor(model => model.UserGender) </div> <div class="editor-field"> @Html.EditorFor(model => model.UserGender) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } </div> </div>

UserName 和 Surname 之類的屬性屬於 String 類型,因此在我的 Shared 文件夾中,我創建了 EditorTemplates 文件夾並創建了一個 String.cshtml 文件來定義 String 編輯器的外觀。 在運行表單測試時,它似乎運行良好,因為生成的輸入字段具有我指定的外觀 - 問題是當我使用這些自定義輸入字段提交表單時,mvc 無法將我的表單字段映射到我的模型。 這樣做的原因是標簽需要支持此綁定到模型的屬性。 下面是一個例子:

這是我在 String.cshtml EditorTemplate 中的代碼:

 <input type="text" class="form-control">

當使用默認的 EditorFor 而不自定義時,它會生成以下標記:

 <input data-val="true" data-val-required="The User Name field is required." id="UserName" name="UserName" type="text" value="" />

正如我們在上面看到的,我的代碼沒有“id”和“name”屬性,它們與我的類中的屬性名稱相關,並且用於將值綁定到我的類。 那么如何更改 String.cshtml 中的代碼以包含這些屬性並動態設置它們的值呢? 因為它應該用於我班級中的各種屬性?

你可以使用這個:

@model string

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
                new
                {
                    @class = "form-control",
                    placeholder = ViewData.ModelMetadata.Watermark 
                                  ?? ViewData.ModelMetadata.DisplayName 
                                  ?? ViewData.ModelMetadata.PropertyName
                })

如果您不想要,請刪除占位符。

回復:占位符,這是對用戶可以在輸入中輸入的內容的提示。 您可以使用注釋來裝飾模型屬性:

[Display(Name = "Client")]
public int ClientId { get; set; }

[Display(Prompt = "Please enter mailing Name")]
public string MailingName { get; set; }

如果你使用這樣的東西,那么你的輸入將具有占位符屬性,其中的值取自這些注釋,按照編輯器模板中指定的順序(提示(水印),名稱,然后屬性名稱)。

不要使用 EditorTemplate 作為 String,只需像這樣使用 TextBoxFor:

@Html.TextBoxFor(model => model.UserName, new { @class = "form-control" })

暫無
暫無

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

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