Reputation: 543
public class EmployeeViewModel
{
public Employee Employee { get; set; }
public IList<Address> Addresses { get; set; }
}
Controller :-
[HttpPost]
public ActionResult InsertAddress(EmployeeViewModel model)
{
//code for insert data into db
}
View :-
Here i want to call InsertAddress action by passing multiple address objects along with single employee object from view to controller .
Is it possible ?
Upvotes: 0
Views: 2432
Reputation: 1186
I have mentioned some common issues while binding complex models, have a look here http://jayakarant.blogspot.de/2014/05/handling-complex-view-models-in-razor.html
Upvotes: 0
Reputation: 1914
You just need to use the correct naming conventions for the model binder to understand.
Property.Property
Or
Property[index].Property for Collections
If index isn't sequential 0 based you need to add a hidden field, Property.Index with the value of the index
Example:
<input name="Employee.Name" value="1234 5678"/>
<input name="Employee.Phone value="1234 5678"/>
<input name="Employee.Email" value="[email protected]"/>
<input name="Addresses.Index" value="0" type="hidden"/>
<input name="Addresses[0].Suburb" value="Melbourne"/>
<input name="Addresses[0].Postcode" value="3000"/>
<input name="Addresses.Index" value="1" type="hidden"/>
<input name="Addresses[1].Suburb" value="Sydney"/>
<input name="Addresses[1].Postcode" value="2000"/>
When your inserting a row, just use the naming convention, and don't forget to add the .Index field.
Most the default EditorFor will handle all of this for you transparently if you create a custom EditorTemplate for your Address class.
Upvotes: 3
Reputation: 41549
Yes it possible, but requires a little work on your part.
Rather than having a single view for the model (with some sort of loop for the addresses), you need to create an EditorTemplate for your Address class, and then in the main view use @Html.EditorFor(m => m.Addresses)
This setup will cause your EmployeeViewModel
instance to be returned to your action containing the full list of Addresses (rather than it being empty).
Upvotes: 2