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>
}
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:
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
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 :@
Use
@required = true
inside the html attributes instead ofdata_val_required = "true"