Making a field as required in Razor view

2019-02-25 06:00发布

问题:

I want to make a text box field as required in the razor view. I can't use validation attribute [Required] because the field names are generated dynamically. I checked this answer which sets the data-val-required field to true using javascript. Is there any other way to do this as I wont be knowing the field id before running the project?

Edit:

I tried the code below and it works now, except that the validation message is not displayed on form submission.

@for (int i = 0; i < Model.Controls.Length; i++)
{
            @Html.TextBoxFor(x => x.Controls[i].Value, new { id = obj.VitalName,  data_val_required = "true" })
            @Html.ValidationMessageFor(x => x.Controls[i].Value, "Please fill in the details.")
        </td>
    </tr>
}

回答1:

Use @required = true inside the html attributes instead of data_val_required = "true"

@Html.TextBoxFor(x => x.Controls[i].Value, new { id = obj.VitalName,  @required = true })


回答2:

If the fields are generated in a partial class, you can implement a buddy class with the metadata for the fields, as shown here: link. If your code is generated by an ORM (Entity Framework for example) the generated classes should be partial. So what you need to do is the following:

  1. Create a class to hold the metadata, give it an appropriate name.
  2. create a partial class (usethe same namespace as the generated class) and decorate it with the MetadataType attribute. The attribute requires a type, which is the class you just created.
  3. Add properties to the metadata class. They must match properties in the generated class exactly, but you don't have to duplicate all properties, only the ones you need. So if you only want to make a property 'Lastname' required, just add

    [Required] public string Lastname { get;set; }

to your class



回答3:

Just for those who are trying to achieve it via @Html.EditorFor, it seems it is not possible to pass some htmlAttributes, do not mistake 'additionalViewData' with 'htmlAttributes' as i did for 2 hours now :@