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_StartこれをGlobal.asax に追加しようとしました

    DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

その結果、まだ検証エラーが発生します。今は次のように表示されています。 ErrorMessage: "A value is required."

これは少し奇妙になってきています。その値が本当に悪いことを望んでいるようです。マシンに幽霊?

4

2 に答える 2

0

これは、フォームからの受信データに値がなかったためです。検証エンジンは値の辞書をチェックし、見つからない場合は ModelState エラーを追加します。int型のデフォルト値なので値は0です。

この問題を解決するには、作成ビューに @Html.HiddenFor(model=>model.Id) を追加するだけです。

于 2011-11-23T14:19:38.850 に答える