関連するフィールドが必要な場合、そのラベルの名前の後に星を付けるラベルの HtmlHelper を作成しました。
public static MvcHtmlString LabelForR<TModel, TValue>(
this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
return LabelHelper(
html,
ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression),
null);
}
private static MvcHtmlString LabelHelper(HtmlHelper helper, ModelMetadata metadata, string htmlFieldName, string text)
{
... //check metadata.IsRequired here
... // if Required show the star
}
ViewModel のプロパティで DataAnnotations を使用して [Required] をスラップすると、プライベート LabelHelper の metadata.IsRequired は True に等しくなり、すべてが意図したとおりに機能します。
ただし、FluentValidation 3.1 を使用して、次のような単純なルールを追加すると:
public class CheckEmailViewModelValidator : AbstractValidator<CheckEmailViewModel>
{
public CheckEmailViewModelValidator()
{
RuleFor(m => m.Email)
.NotNull()
.EmailAddress();
}
}
... 私の LabelHelper メタデータでは、IsRequired が誤って false に設定されます。(ただし、バリデーターは機能します。空のフィールドを送信することはできず、電子メールのようなものである必要があります)。
残りのメタデータは正しいように見えます (例: metadata.DisplayName = "Email")。
理論的には、Rule .NotNull() が使用されている場合、FluentValidator はプロパティで RequiredAttribute を平手打ちします。
参考までに:私のViewModel:
[Validator(typeof(CheckEmailViewModelValidator))]
public class CheckEmailViewModel
{
//[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
私のコントローラー:
public class MemberController : Controller
{
[HttpGet]
public ActionResult CheckEmail()
{
var model = new CheckEmailViewModel();
return View(model);
}
}
どんな助けでも大歓迎です。