I use ASP.NET MVC 2, with Visual Studio 2008 and my view is strongly-typed. The validation using ValidationAnnotation works.
What I’m trying to find is how to launch the validation when opening the form. When it opens the model has error, but error doesn’t show up. When I press the submit button, the controller validates the model and return to the form.
Public Function EditVente(ByVal pNoEnreg As Integer) As ActionResult
Dim dossierVente As VenteDansMedianePlus = model.Helper.selectDossierVente(pNoEnreg)
Return View(dossierVente)
End Function
Public Function enregistrerVente(ByVal pVente As VenteDansMedianePlus) As ActionResult
If ModelState.IsValid Then
model.Helper.updateDossierVente(pVente)
Return RedirectToAction("EditVente", "A009P003", New With {Key .pNoEnreg = pVente.noEnreg})
Else
Return View("EditVente", pVente)
End If
End Function
I try to put ModelState.IsValid in the editVente function, but it doesn’t work.
My question is how to launch the model validation before returning the view, so the view has the error message.
I think you’re looking for the TryUpdateModel-method. You can call this method on your controller and pass in your model: (Sorry, I’m a C# developer, hope this is correct)
For more information, check this SO post: When and why do you use TryUpdateModel in asp.net mvc 2?
Edit
The TryUpdateModel-method works about the same as the UpdateModel-method, except that UpdateModel throws errors when the validation fails, where TryUpdateModel doesn’t.