一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性。ASP.NET MVC?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (299)

我遇到了错误显示为我的标题。我试图寻找解决方案,但我得到的只是使用try catch代码块的解决方案。

我一直在使用我所做的课程文档来指导我做这个项目,但是这次我遇到的错误,我对哪个部分出错以及如何检查错误部分一无所知。

我用// strange评论评论了两个部分,这意味着我不知道错误发生的地方或类似的地方。

感谢您阅读我的问题。

这是我的PetRescued模型

public class PetRescued
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string PetName { get; set; }

    public int PetAge { get; set; }

    [Required]
    [StringLength(6)]
    public string PetGender { get; set; }

    public short PetWeightInKg { get; set; }

    public DateTime DateWhenRescued { get; set; }

    public PetSpecies PetSpecies { get; set; }

    public byte PetSpeciesId { get; set; }

}

这是我的PetRescued控制器

[HttpPost]
public ActionResult Save(PetRescued petRescued)
{
    if (petRescued.Id == 0)
        _context.PetRescueds.Add(petRescued);
    else
    {
        var petRescuedInDb = _context.PetRescueds.Single(c => c.Id == petRescued.Id);
        petRescuedInDb.PetName = petRescued.PetName;
        petRescuedInDb.PetAge = petRescued.PetAge;
        petRescuedInDb.PetGender = petRescued.PetGender;
        petRescuedInDb.PetWeightInKg = petRescued.PetWeightInKg;
        petRescuedInDb.PetSpeciesId = petRescued.PetSpeciesId; //strange
        petRescuedInDb.DateWhenRescued = petRescued.DateWhenRescued;
     }

    _context.SaveChanges();
    return RedirectToAction("Index", "PetRescued");
}

这是我的PetRescued ViewModel

public class PetRescuedViewModel
{
    public IEnumerable<PetSpecies> PetSpecies { get; set; }

    public PetRescued PetRescueds { get; set; }


    public PetRescuedViewModel()
    {
        PetRescueds = new PetRescued(); 
    }
}

这是我的PetRescued表格

@using (Html.BeginForm("Save", "PetRescued"))
{
<div class="form-group">
    @Html.LabelFor(m => m.PetRescueds.PetName)
    @Html.TextBoxFor(m => m.PetRescueds.PetName, new { @class = "form-control" })
</div>

//strange
<div class="form-group">
    @Html.LabelFor(m => m.PetSpecies)
    @Html.DropDownListFor(m => m.PetRescueds.PetSpeciesId, new SelectList(Model.PetSpecies, "Id", "SpeciesName"), "Select A Species", new {@class = "form-control"})    
</div>

<div class="form-group">
    @Html.LabelFor(m => m.PetRescueds.PetAge)
    @Html.TextBoxFor(m => m.PetRescueds.PetAge, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(m => m.PetRescueds.PetGender)
    @Html.TextBoxFor(m => m.PetRescueds.PetGender, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(m => m.PetRescueds.PetWeightInKg)
    @Html.TextBoxFor(m => m.PetRescueds.PetWeightInKg, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(m => m.PetRescueds.DateWhenRescued)
    @Html.TextBoxFor(m => m.PetRescueds.DateWhenRescued, "{0:d MMM yyyy}", new { @class = "form-control" }) 
</div>

@Html.HiddenFor(m => m.PetRescueds.Id)
<button type="submit" class="btn btn-primary">Save</button>
}
提问于
用户回答回答于

看看你的模型定义

// This means this value is required 
// and should not be greater than 255 characters 
[Required]
[StringLength(255)]
public string PetName { get; set; }

// This means this value is required 
// and should not be greater than 6 characters 
[Required]
[StringLength(6)]
public string PetGender { get; set; }

因此,要么您没有从客户端应用程序发送值,要么它大于您声明的限制。将您的操作方法更改为此以在后端验证您的模型(您永远不应该信任客户端输入)

[HttpPost]
public ActionResult Save(PetRescued petRescued)
{
    if (ModelState.IsValid) // Check for errors
    {
        if (petRescued.Id == 0)
            _context.PetRescueds.Add(petRescued);
        else
        {
            var petRescuedInDb = _context.PetRescueds.Single(c => c.Id == petRescued.Id);
            petRescuedInDb.PetName = petRescued.PetName;
            petRescuedInDb.PetAge = petRescued.PetAge;
            petRescuedInDb.PetGender = petRescued.PetGender;
            petRescuedInDb.PetWeightInKg = petRescued.PetWeightInKg;
            petRescuedInDb.PetSpeciesId = petRescued.PetSpeciesId; //strange
            petRescuedInDb.DateWhenRescued = petRescued.DateWhenRescued;
         }

        _context.SaveChanges();
        return RedirectToAction("Index", "PetRescued");
    }
    else
        return View(petRescued); // Return the same view with the original data
                                 // or with the correct model of your view, at least
}

然后,更改视图以包括从服务器检索的验证错误

@using (Html.BeginForm("Save", "PetRescued"))
{
<!-- This will show your errors-->
@Html.ValidationSummary()
<div class="form-group">
    @Html.LabelFor(m => m.PetRescueds.PetName)
    <!-- Or you can show errors for each model property -->
    <!-- like this -->
    @Html.ValidationMessageFor(m => m.PetRescueds.PetName);
    @Html.TextBoxFor(m => m.PetRescueds.PetName, new { @class = "form-control" })
</div>

//strange
<div class="form-group">
    @Html.LabelFor(m => m.PetSpecies)
    @Html.DropDownListFor(m => m.PetRescueds.PetSpeciesId, new SelectList(Model.PetSpecies, "Id", "SpeciesName"), "Select A Species", new {@class = "form-control"})    
</div>

<div class="form-group">
    @Html.LabelFor(m => m.PetRescueds.PetAge)
    @Html.TextBoxFor(m => m.PetRescueds.PetAge, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(m => m.PetRescueds.PetGender)
    @Html.TextBoxFor(m => m.PetRescueds.PetGender, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(m => m.PetRescueds.PetWeightInKg)
    @Html.TextBoxFor(m => m.PetRescueds.PetWeightInKg, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(m => m.PetRescueds.DateWhenRescued)
    @Html.TextBoxFor(m => m.PetRescueds.DateWhenRescued, "{0:d MMM yyyy}", new { @class = "form-control" }) 
</div>

@Html.HiddenFor(m => m.PetRescueds.Id)
<button type="submit" class="btn btn-primary">Save</button>
}

您可以在Microsofts上阅读有关数据验证的更多信息

用户回答回答于

让我们试着解决这个问题吧。

首先,让我们更改您的控制器,以便能够对模型绑定器返回的错误执行某些操作。

[HttpGet]
public ActionResult Save() // Or whatever controller action that renders your form
{
    PetRescuedViewModel viewModel = new PetRescuedViewModel();
    viewModel.PetSpecies = _someMethod.ToPopulate();  // populate the list

    return View(viewModel);
}

[HttpPost]
public ActionResult Save(PetRescuedViewModel viewModel)
{
    if (ModelState.IsValid) // Check for errors
    {
        if (petRescued.Id == 0)
            _context.PetRescueds.Add(petRescued);
        else
        {
            var petRescuedInDb = _context.PetRescueds.Single(c => c.Id == petRescued.Id);
            petRescuedInDb.PetName = viewModel.PetRescued.PetName;
            petRescuedInDb.PetAge = viewModel.PetRescued.PetAge;
            petRescuedInDb.PetGender = viewModel.PetRescued.PetGender;
            petRescuedInDb.PetWeightInKg = viewModel.PetRescued.PetWeightInKg;
            petRescuedInDb.PetSpeciesId = viewModel.PetRescued.PetSpeciesId; //strange
            petRescuedInDb.DateWhenRescued = viewModel.PetRescued.DateWhenRescued;
        }

        _context.SaveChanges();
        return RedirectToAction("Index", "PetRescued");
    }

    viewModel.PetSpecies = _someMethod.ToPopulate();  // populate the list again

    return View(viewModel); // validation errors found, so redisplay the same view
}

然后,更改视图以显示错误。我们基本上是在做这个答案所暗示的。

@using (Html.BeginForm("Save", "PetRescued"))
{
    // Displays a summary of all the errors.
    @Html.ValidationSummary() 

    <div class="form-group">
        @Html.LabelFor(m => m.PetRescueds.PetName)
        @Html.TextBoxFor(m => m.PetRescueds.PetName, new { @class = "form-control" })
        // Or you can add this to each property            
        @Html.ValidationMessageFor(m => m.PetRescueds.PetName) 
    </div>

    //strange
    <div class="form-group">
        @Html.LabelFor(m => m.PetSpecies)
        @Html.DropDownListFor(m => m.PetRescueds.PetSpeciesId, new SelectList(Model.PetSpecies, "Id", "SpeciesName"), "Select A Species", new {@class = "form-control"})    
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.PetRescueds.PetAge)
        @Html.TextBoxFor(m => m.PetRescueds.PetAge, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.PetRescueds.PetGender)
        @Html.TextBoxFor(m => m.PetRescueds.PetGender, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.PetRescueds.PetWeightInKg)
        @Html.TextBoxFor(m => m.PetRescueds.PetWeightInKg, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.PetRescueds.DateWhenRescued)
        @Html.TextBoxFor(m => m.PetRescueds.DateWhenRescued, "{0:d MMM yyyy}", new { @class = "form-control" }) 
    </div>

    @Html.HiddenFor(m => m.PetRescueds.Id)
    <button type="submit" class="btn btn-primary">Save</button>
}

上述更改将至少为您提供哪些属性存在问题。

下一步是解决实际问题。如果您执行上述操作并且无法进一步弄清楚,请告诉我它是哪些属性,我会看看。

我猜它是,public byte PetSpeciesId { get; set; }但让我们看看。

希望这可以帮助。

扫码关注云+社区

领取腾讯云代金券