【问题标题】:ModelState.IsValid is validating referenced entityModelState.IsValid 正在验证引用的实体
【发布时间】:2018-12-11 16:16:46
【问题描述】:

我有以下实体:

public class Ambiente
{
    public int AmbienteId { get; set; }

    [Display(Name ="Codigo del Ambiente")]
    [StringLength(10, ErrorMessage ="El ancho máximo es de 10 caracteres")]
    public string Codigo { get; set; }

    [Display(Name ="Nombre del Ambiente")]
    [StringLength(50, ErrorMessage ="El ancho máximo es de 50 caracteres")]
    public string Nombre { get; set; }

    [Required(ErrorMessage ="Especifique una etapa")]
    [Display(Name ="Nombre de la Etapa")]
    public Etapa Etapa { get; set; }
}

如你所见,这个类有一个属性,它引用了一个名为 Etapa 的实体

public class Etapa
{
    public int EtapaId { get; set; }

    [Required(ErrorMessage ="Especifique un nombre de Etapa")]
    [StringLength(20, ErrorMessage = "El ancho maximo es de 20")]
    [Display(Name ="Nombre de la Etapa")]
    public string Nombre { get; set; }
}

这个类 Etapa 对属性 Nombre 进行了验证。现在关于 Ambiente 类,在提交数据以插入数据库时​​,我在 Insertar Action 中使用此代码:

[HttpPost]
public IActionResult Insertar(Ambiente ambiente)
{
    if (ModelState.IsValid)
    {
        try
        {
            _ambienteRepository.Insertar(ambiente);
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.Message);
        }
    }
    var ambienteViewModel = ObtenerAmbienteViewModel(ambiente);
    return View(ambienteViewModel);
}

当此代码到达 ModelState.IsValid 语句时,它会抛出 false 并出现以下消息:

“Especifique un nombre de Etapa”

这是我的 Etapa 类的属性 Nombre 的文本。

当我通过 Insertar Action 中的参数快速查看变量环境时,我看到以下内容:

这个 Etapa 实体用于在我的视图中填充下拉列表。所有值都已存在于数据库中,因此我不打算向该实体添加记录。

我不知道如何绕过这个引用实体 Etapa 的验证。

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc asp.net-core-mvc-2.1


    【解决方案1】:

    正常的方法是创建一个 viewmodel ,不要包含 Etapa 属性。在插入数据库之前为服务器端的Ambiente 对象赋值。

    如果你不想改变任何东西。根据您的代码,您可以忽略 Etapa 的模型状态错误(但不是一个好主意):

    ModelState.Remove("Etapa");
    

    然后分配所需的Etapa 以确保Nombre 不为空。代码如下:

    ModelState.Remove("Etapa");
    if (ModelState.IsValid)
    {
        var etapa = _context.Etapa.First(a => a.EtapaId == ambiente.Etapa.EtapaId);
        ambiente.Etapa = etapa;
        _context.Add(ambiente);
        await _context.SaveChangesAsync();
        .....
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      相关资源
      最近更新 更多