ValidationResult和ViewModels

时间:2012-11-29 17:43:29

标签: c#-4.0 asp.net-mvc-4 entity-framework-5

我最近创建了一个使用MVC4和EF5的新应用程序。这些表已经存在,所以我们首先使用数据库。这对我来说都是新手,这是我第一次参加MVC或EF。

我的EMDX文件中有一些模型,其中一个模型我继承了IValidatableObject并在Validate函数中放了一些代码。这工作正常,然后我改变了我的视图使用ViewModel,现在我从验证中得到一个错误,我很难过。它仍在调用我的验证功能,但不再将其发回屏幕,我只是得到一个黄色的屏幕。

错误:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

型号:

public partial class Names : IValidatableObject {
  public int Id { get; set; }
  public string Name { get; set; }
  public bool Active { get; set; }

  public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
    // some logic, this works
  }
}

视图模型:

public class NamesVM {
  public Names Name { get; set; }
  // some other stuff in this model, but not part of this problem
}

控制器:编辑功能:

[HttpPost]
public ActionResult Edit(NamesVM nvm) {

  if (ModelState.IsValid) {
    dbCommon.Entry(nvm.Name).State = EntityState.Modified;
    dbCommon.SaveChanges();
    return RedirectToAction("Index");
  }

  return View(nvm);
}

查看:

@model NamesVM
<div class="editor-label">
  @Html.LabelFor(model => model.Name.Id)
</div>
<div class="editor-field">
  @Html.EditorFor(model => model.Name.Id)
  @Html.ValidationMessageFor(model => model.Name.Id)
</div>

<div class="editor-label">
  @Html.LabelFor(model => model.Name.Name)
</div>
<div class="editor-field">
  @Html.EditorFor(model => model.Name.Name)
  @Html.ValidationMessageFor(model => model.Name.Name)
</div>

<div class="editor-label">
  @Html.LabelFor(model => model.Name.Active)
</div>
<div class="editor-field">
  @Html.EditorFor(model => model.Name.Active)
  @Html.ValidationMessageFor(model => model.Name.Active)
</div>
<input type="submit" value="Save" />

如果屏幕上的所有内容都正确,代码工作正常,但是当验证失败时,我没有得到错误,我得到一个黄色的屏幕。我确信我错过了什么,我只是不知道是什么。

1 个答案:

答案 0 :(得分:0)

终于解决了它。需要将IValidatableObject移动到ViewModel及其逻辑。

模型

public partial class Names { //: IValidatableObject { //Remove the IValidateableObject from here
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }

    // this whole method can be commented out
    //public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        // some logic, this works
    //}
}

查看模型

public class NamesVM : IValidatableObject { // add the IValidatableObject to your view model
    public Names Name { get; set; }
        // some other stuff in this model, but not part of this problem

    // and move your validation logic to here
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        // some logic, this works
    }
}