Un changement mineur, c’est que je n’utilise plus le FluentValidationModelValidatorProvider mais le standard. Donc j’ai décorer le modèle d’affichage avec les annotations de données nécessaires :
[Validator(typeof(UserViewModelValidator))]
public class UserViewModel
{
public int Id { get; set; }
[DisplayName("First name *")]
public string FirstName { get; set; }
[DisplayName("Last name *")]
public string LastName { get; set; }
public int? Age { get; set; }
}
Et le validateur devient :
public class UserViewModelValidator : AbstractValidator
{
public UserViewModelValidator()
{
RuleFor(x => x.FirstName)
.NotEmpty()
.WithMessage("First name is required");
RuleFor(x => x.LastName)
.NotEmpty()
.WithMessage("Last name is required");
}
}
Et Voici les vues correspondantes à l’aide de rasoir :
Index.cshtml
@model IEnumerable
@{
ViewBag.Title = "Index";
}
Index
@(Html
.Grid(Model)
.Columns(column => {
column.Custom(model => Html.Partial("_TableLinks", model));
column.For(model => model.FirstName);
column.For(model => model.LastName);
column.For(model => model.Age);
})
)
@(Html.ActionLink(c => c.New(), "Create New"))
_TableLinks.cshtml
@model SampleMvc.Web.Models.UserViewModel
@(Html.ActionLink(c => c.Edit(Model.Id), "Edit")) |
@(Html.ActionLink(c => c.Show(Model.Id), "Details")) |
@using (Html.BeginForm(c => c.Destroy(Model.Id)))
{
@Html.HttpMethodOverride(HttpVerbs.Delete)
}
Edit.cshtml
@model SampleMvc.Web.Models.UserViewModel
@{
ViewBag.Title = "Edit";
}
Edit
@using (Html.BeginForm(c => c.Update(null)))
{
@Html.ValidationSummary(true)
@Html.HttpMethodOverride(HttpVerbs.Put)
@Html.HiddenFor(model => model.Id)
@Html.EditorForModel()
}
@(Html.ActionLink(c => c.Index(), "Back to List"))
New.cshtml
@model SampleMvc.Web.Models.UserViewModel
@{
ViewBag.Title = "New";
}
New
@using (Html.BeginForm(c => c.Create(null)))
{
@Html.ValidationSummary(true)
@Html.EditorForModel()
}
@(Html.ActionLink(c => c.Index(), "Back to List"))
Show.cshtml
@model SampleMvc.Web.Models.UserViewModel
@{
ViewBag.Title = "Show";
}
Show
@Html.DisplayForModel()
@(Html.ActionLink(c => c.Edit(Model.Id), "Edit")) |
@(Html.ActionLink(c => c.Index(), "Back to List"))
Modèle de l’éditeur UserViewModel.cshtml
@model SampleMvc.Web.Models.UserViewModel
Fields
@Html.LabelFor(model => model.FirstName)
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
@Html.LabelFor(model => model.LastName)
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
@Html.LabelFor(model => model.Age)
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
Modèle d’affichage UserViewModel.cshtml
@model SampleMvc.Web.Models.UserViewModel
Fields
Id
@Html.DisplayFor(x => x.Id)
FirstName
@Html.DisplayFor(x => x.FirstName)
LastName
@Html.DisplayFor(x => x.LastName)
Age
@Html.DisplayFor(x => x.Age)
Le code source est disponible sur github.