0

我有以下实体:

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 的验证。

4

1 回答 1

0

正常的方法是创建一个 viewmodel ,不包括Etapaproperty 。在插入数据库之前将值分配给Ambiente服务器端的对象。

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

ModelState.Remove("Etapa");

然后分配 requiredEtapa以确保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();
    .....
}
于 2018-12-12T06:51:58.443 回答