1

I am trying to use @Html.ValidationMessage like the following:

@Html.TextBox(Model.Key, "", attr)
@Html.ValidationMessage(Model.Key)

However, my validation message isn't displaying.

If I print my Model.Key to the screen, I get "FirstName", however if I look at the source that is created for the above code, it creates it like this:

<input name="FirstName" class="form__control" data-msg-maxlength="This field is limited to 200 characters" data-rule-maxlength="200" data-rule-required="true" id="FirstName" placeholder="Please enter your first name" type="text" value="">
<span class="field-validation-valid" data-valmsg-for="field.FirstName" data-valmsg-replace="true"></span>

Does anyone know why it is prepending the field. to that validation message span or how I can get rid of it?

I have tried typing it in manually:

@Html.ValidationMessage("FirstName")

And this still seems to prepend the field.

Update

Could it be something to do with me using @Html.EditorFor(_ => field) to call a partial that has the textbox and validation message? - If I put the ValidationMessage next to the EditorFor then it works properly (but is out of position)

Pete
  • 57,112
  • 28
  • 117
  • 166
  • Do you have a [Required] in the model? – Animus Miles-Militis Sep 01 '17 at 11:16
  • No, I create the model error manually: ModelState.AddModelError("FirstName", "Error"); – Pete Sep 01 '17 at 11:19
  • Are you doing this in a loop? –  Sep 01 '17 at 11:20
  • @StephenMuecke I do the editorfor bit in a loop: `@foreach (var field in group.FieldGroup) { @Html.EditorFor(_ => field) }` – Pete Sep 01 '17 at 11:21
  • 2
    Then that's you problem. And it will create others problems such as not being able to bind to your model. You need to use a `for` loop or `EditorTemplate` as explained in [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) –  Sep 01 '17 at 11:23
  • Ah brilliant, thanks @StephenMuecke, I will close as duplicate – Pete Sep 01 '17 at 11:28

1 Answers1

-1

just do like this

public class A
    {
        public int id { get; set; }
        [Required(ErrorMessage = "Please Enter Name")]
        public string name { get; set; }
}
hitesh panwar
  • 40
  • 1
  • 10