1

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
James in Indy
  • 2,804
  • 2
  • 25
  • 25

1 Answers1

1

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.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • That's what I was afraid of, but thanks for giving me the answer. About TryUpdateModel(), I think that was leftover from when the method took a FormCollection; I'll look into that. – James in Indy Aug 14 '12 at 11:58