I have a strongly typed razor view for a model in my MVC 3 project. Basically its for editing the model.
The model contains an Id field for the database key and some other string fields (Its a viewModel and all but thats not the point of the question).
In the view I just have a form and a submit button and nothing else. When the View is posted to the controller the model in the controller has all fields empty EXCEPT for the Id field which seems to have been auto-magically filled up.
How and where does the Id field gets populated in the model without there being a corresponding ‘input’ element for it in the view.
This is probably a dumb question but I would appreciate even just a link to what I should read up on. Thanks.
I bet it comes from the url as route parameter.
For example you have the following controller:
and the following view:
Now you navigate to GET
/home/index/123and you get the following markup:Notice the
actionattribute of the form? That’s where the id comes from. Basically theHtml.BeginForm()helper uses the current url when generating the action attribute, and since the current url is/home/index/123it is what gets used.And because if you have left the default routes in your Global.asax, the
{id}route token is used at the end of the url, the default model binder successfully binds it to theIdproperty of your view model.