Wednesday, December 19, 2018

RequireIfValue in .NET Core MVC

If you have a getsetter like this in your model:

[RequireIfValue(nameof(FooId), 13, ErrorMessage = "You must select a bar id!")]
[Display(Name = "Bar Id")]
public int? BarId { get; set; }

 
 

Then if you fill out a form in Razor and you set FooId to 13 and you do not set the BarId you will get this error here in the Razor markup:

<span asp-validation-for="@Model.BarId" class="text-danger"></span>

 
 

Addendum 1/10/2019: @Html.LabelFor(model => model.BarId) is an example of what the Display attribute wires up to.

No comments:

Post a Comment