1

我有这个 ViewModel:

    [Key]
    public long KlijentID { get; set; }

    [Required(ErrorMessageResourceName = "RequiredField", ErrorMessageResourceType = typeof(Resources))]
    [StringLength(50, ErrorMessageResourceName = "StringLength50", ErrorMessageResourceType = typeof(Resources))]
    public string ImePrezime { get; set; }

    [Required(ErrorMessageResourceName = "RequiredField", ErrorMessageResourceType = typeof(Resources))]
    [StringLength(50, ErrorMessageResourceName = "StringLength50", ErrorMessageResourceType = typeof(Resources))]
    public string Adresa { get; set; }

    //Rest of the Class, not important for the question.

在我看来,我有:

    @using (Html.BeginForm("Edit", "Klijenti"))
    {
     @Html.HiddenFor(model => model.KlijentID)

     <div class="editor-label">
        @Html.LabelFor(model => model.ImePrezime)
     </div>
     <div class="editor-field">
        @Html.EditorFor(model => model.ImePrezime)
        @Html.ValidationMessageFor(model => model.ImePrezime)
     </div>
     <div class="editor-label">
        @Html.LabelFor(model => model.Adresa)
     </div>
     <div class="editor-field">
        @Html.EditorFor(model => model.Adresa)
        @Html.ValidationMessageFor(model => model.Adresa)
     </div>
     <p><input type="submit" value="Spremi" /><p>
    }

当我使用它从数据库更新对象时,控制器操作工作正常:

    if (!ModelState.IsValid) throw new ValidationException();
    var k=new Klijent();
    Mapper.Map(klijent, k);
    repo.SaveKlijent(k);
    TempData["msg"] = MyResources.Properties.Resources.SaveDone;
    return RedirectToAction("Index", page);

但是当我尝试添加一个新对象时,ModelState.IsValid失败说需要 KlijentID。 ErrorMessage:"The KlijentID field is required."

我已经检查过了,它被设置为 0,因为它应该是一个新对象。这里有什么问题?

更新: 我试图将此添加到我Application_StartGlobal.asax

    DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

结果是我仍然收到验证错误,刚才它说: ErrorMessage: "A value is required."

这有点奇怪,它似乎只是想要这个值真的很糟糕。机器里有鬼?

4

2 回答 2

0

这是因为从表单传入的数据没有任何价值。验证引擎检查值字典,如果未找到,则添加 ModelState 错误。值等于 0,因为它是 int 类型的默认值。

要解决这个问题,只需在您的 Create 视图中添加 @Html.HiddenFor(model=>model.Id) 。

于 2011-11-23T14:19:38.850 回答
0

我有同样的问题。我将我的主键设置为可空类型,一切都像一个魅力。

于 2015-09-02T19:20:30.787 回答