Is there a possibility in ASP.NET MVC3 to set the properties of a view model from a FormCollection
without invoking validation specified by validation attributes on the properties?
UpdateModel<T>(T model)
also invokes validation.
The background:
I can only validate the model if a connection to the database is present, but this connection can only be established, if the data from one specific form field is correct (kind of an access code fo开发者_运维知识库r each organisation). If the connection is not established, an exception is thrown.
When the data entered in this field is incorrect, I don't want to loose the values entered in all other form fields, but present the already entered values again to the user and give him a change to correct the errors.
So what I need is basically something like conditional validation or no validation by the model binder at all. Is there anything like this built-in in ASP.NET MVC or do I need to write my own UpdateModel method, calling a (custom) model binder?
Why not pass the viewmodel into your method, rather than formscollection? That way you can do
[HttpPost]
public ActionResult Update(UpdateViewModel model)
{
if (!Model.IsValid)
{
return View(model);
}
}
So if the validation fails your user is going to be directed back to the Update view, with the model already populated from the information they submitted.
Now, in my opinion, having a validation attribute require a database connection, which in turn can throw exceptions is the wrong way to go about this. Those sorts of validation I move to a validation service, which is injected into the controller (and takes in the repository stuff it needs via DI as well). Each validation service will take in a view model and return a collection of ValidationResult instances, which I then attach to the model validation results via an extension method to the Controller class (both lifted from the Project Silk stuff MS P&P is pushing out)
This allows for easier testing as you can mock up the repository and have it return the correct results for testing ...
精彩评论