Question

I'd like to create template for string, that will include label, textbox with watermark and validation message for registration form. In addition, I'd like to add notice (eg. star), that the field is required by getting it from model.

So far I have created file string.cshtml in ~/Views/Account/EditorTemplates containing this:

<span class="editor-label>@Html.Label(ViewData.ModelMetadata.Watermark)</span>
<span class="editor-field">@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { placeholder =  ViewData.ModelMetadata.Watermark })</span>
<span class="error_message">@Html.ValidationMessage(ViewData.ModelMetadata.PropertyName)</span>

Model looks like this:

    [Required]
    [DataType(DataType.Text)]
    [Display(Prompt = "First name")]
    public string FirstName { get; set; }

And in view I call it as follows:

@Html.EditorFor(m => m.FirstName)

Does anyone have any idea, where do I go wrong?

Was it helpful?

Solution

Your editor template must be called Text.cshtml and not String.cshtml because you use the [DataType(DataType.Text)] attribute.

You could also specify a custom name for the editor template using the UIHint attribute:

[Required]
[DataType(DataType.Text)]
[Display(Prompt = "First name")]
[UIHint("Foo")]
public string FirstName { get; set; }

and now you could have ~/Views/Account/EditorTemplates/Foo.cshtml.

OTHER TIPS

Andree,

Your problem for not showing the message is this line:

<span class="error_message">@Html.ValidationMessage(ViewData.ModelMetadata.PropertyName)</span>

If you look at your rendered HTML source, you see something like the following:

<span class="field-validation-error" data-valmsg-for="<className>.FirstName" data-valmsg-replace="true"></span>

Notice, that it's including the class in the data attribute. However, ubobtrusive doesn't match this. What you need rendered is simply:

<span class="field-validation-error" data-valmsg-for="FirstName" data-valmsg-replace="true"></span>

In order to accomplish this, change your code in your editor to:

@Html.ValidationMessageFor(v => v)

Likewise, to make you code easier to read, both of these also work for your other code...

@Html.LabelFor(v => v)
@Html.TextBoxFor(v => v, new { placeholder = ViewData.ModelMetadata.Watermark })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top