0
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 :- enter image description here

Here i want to call InsertAddress action by passing multiple address objects along with single employee object from view to controller .

Is it possible ?

0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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).

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.