【问题标题】:Validate Model in View when the Model is a List<SomeModel>当模型是 List<SomeModel> 时验证视图中的模型
【发布时间】:2019-08-20 19:28:17
【问题描述】:

我有一个 asp.net core 3.0 MVC 应用程序。在这个应用程序中,我可以列出、创建、编辑和删除一些对象(数据行)。 所有这些操作都有视图:

  • /Index.csltml(datagridview 中所有项目的列表)
  • /Create.cshtml
  • /Update.cshtml
  • /Delete.cshtml

所有这些,包括。验证工作得很好。但我找不到验证索引中项目的方法。 当我使用应用程序编辑项目时,输入得到验证,我无法输入无效数据。 但是当数据已经无效加载时,显示视图时没有提示。 特别是在索引视图中,我想在每个受影响的行中显示某种警告指示器。

有没有办法在遍历列表时在视图中验证模型?或者有更好的方法吗?

//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);
}

【问题讨论】:

  • 您使用哪个库来验证表单中的数据,然后再将其发布到服务器。加载页面后,您可以通过调用 validate 方法来执行相同操作。
  • 我使用的是普通的 asp.net core 3.0。验证发生在管道内。
  • 您想要客户端还是服务器端验证?
  • 尽可能作为服务器端。我更喜欢控制器中的 ModelState 之类的东西,但在 view/*.cshtml 中。
  • 我知道你想要什么,这是一个答案stackoverflow.com/questions/17138749/…

标签: c# validation asp.net-core model-view-controller


【解决方案1】:

其实很简单。 Like mentioned in this great tutorial.

@using System.ComponentModel.DataAnnotations
<tbody>
    @foreach (SomeModel m in Model)
    { 
        ValidationContext vc = new ValidationContext(m);
        ICollection<ValidationResult> results = new List<ValidationResult>(); 
        bool isValid = Validator.TryValidateObject(m, vc, results, true);
    }
</tbody>

【讨论】:

    猜你喜欢
    • 2011-04-04
    • 2010-11-18
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多