私はこの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."
これは少し奇妙になってきています。その値が本当に悪いことを望んでいるようです。マシンに幽霊?