MVC3 How to modify incoming model before TryUpdate?

312 views Asked by At

This should be simple, but I'm not seeing it, so I hope somebody can help (all my posts probably start this way). So I have a model coming into a controller.

[HttpPost]
public ActionResult Index(Policy screenModel)

I want to do something specific to that model before it updates, for example:

If (condition)
    screenModel.AgentNumber = 1000;

Now I need to get screenModel back into the ValueProvider before TryUpdateModel or ModelState.IsValid fires, or else the change doesn't do anything. If I was accepting a FormCollection in the method, I could simply do this:

this.ValueProvider = collection.ToValueProvider();

But there are other reasons I'm not using a FormCollection. How do I get an object back into the ValueProvider?

1

There are 1 answers

1
Erik Funkenbusch On BEST ANSWER

First, you aren't supposed to call TryUpdateModel or UpdateModel when using methods with models passed as parameters. These basically do the UpdateModel before the method is called.

Second, UpdateModel is designed to copy objects from the FormsCollection to a model, and it will overwrite anything you put in there.

Third, ModelState is also updated prior to the method being called.

If you want to do this sort of thing, then a custom model binder is probably the way to go.