I have this 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.
In the view i have:
@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>
}
When i use it to update an object from database the controller action works fine:
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);
But when i try to add a new object, than the ModelState.IsValid
fails saying that the KlijentID is required.
ErrorMessage:"The KlijentID field is required."
I have checked, it is set as 0 as it should be for a new object. What is the problem here?
UPDATE:
I have tried to add this to my Application_Start
in Global.asax
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
The result is i still get a validation error, just now it says:
ErrorMessage: "A value is required."
This is getting a bit strange, it just seems to want that value really bad. Ghosts in the machine?