I have a feeling this could be a basic question!
I have a complex object ie a document object which contains properties that are lists of other objects. It has been created by deserializing some XML.
I would like to pass the entire Model to the View
Return ViewResult(MyDoc)
In the View some properties are edited. Control is then returned back to the Post Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Document myDoc)
“myDoc” now just represents my Form’s fields. I suspect this is ModelBinding at work. So I guess I need to persist my complex object in a hidden field(example would be great) or as a session object. However I am a bit confused how my updated field gets merged back into the persisted object(hidden or session).
You are right, this is model binding at work.
The binding occurs almost automatically when you use HtmlHelpers such as :
This line actually creates something a little bit like this :
Then when you submit your form, the
DefaultModelBinderis able to deserialize the POST value and create and object of the given type (at least it will try), if it can’t find a corresponding entry, the property will be null and if an entry have no corresponding property, it will be ignored (unless you have other parameters).You can read this article it’s a little bit old, but it’s still pretty accurate.
As an exemple:
Let’s say you have a simple object :
A simple controler :
And a simple view :
You will see, when you submit the form, that the model is recreated completely.
If you don’t want to display the actual value of a property, but still need it persisted:
This will generate a hidden field that will be posted back and, therefor, persisted.
Happy coding !