我有这个 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."
这有点奇怪,它似乎只是想要这个值真的很糟糕。机器里有鬼?