I have a asp.net core 3.0 MVC app. In this app I can List, Create, Edit and delete some objects (datarows). There are views for all of these operations:
- /Index.csltml (List of all items in a datagridview)
- /Create.cshtml
- /Update.cshtml
- /Delete.cshtml
All this, incl. validation works very fine. But I cant find a way to validate the items in the index. When I edit the items with the app, the input gets validated and I cant enter invalid data. But when the data are already invalid loaded, there is no hint when the view is shown. Especially in the index view, I want to show some kind of a warning indicator in each affected row.
Is there a way to validate the model in a view when iterating through a list of it? Or is there a better approach for this?
//Index View
@model List<SomeModel>
<tbody>
@foreach (SomeModel m in Model)
{
//... Validation here please!
}
</tbody>
public class SomeModel : IValidatableObject
{
[Required()]
public Guid ModelId;
[Required()]
[StringLength(50, MinimumLength = 5)]
public string ModelProperty:
...
more properties
...
IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
}
}
public class SomeController
{
[HttpGet()]
public IActionResult Index()
{
List<SomeModel> _models = SomeModel.GetModels();
return View(_models);
}
}
[HttpPost()]
[Route("Create")]
public IActionResult HttpPostCreate(SomeModel _model)
{
// When posting data, the data arrives validated in the controller method
if (ModelState.IsValid)
{
bool success = SomeModel.CreateSetting(_model);
if (success)
{
return RedirectToAction("Index");
}
}
return View("Create", _model);
}