I have problem when I am trying to pass values back from my page which contains the same partial view twice.
My class definiton is like below:
public class Account : IEntity
{
public decimal CurrentBalance { get; set; }
public List<Person> AccountHolders { get; set; }
//to get round the non-existing enum support in EF4.3 wrap enum to int
public int StatusValue { get; set; }
public AccountStatus Status { get { return (AccountStatus)StatusValue; } set { StatusValue = (int) value; } }
public DateTime AccountOpenDate { get; set; }
public DateTime AccountCloseDate { get; set; }
public DateTime AccountSuspensionDate { get; set; }
}
It has a List of Person , which I made a partial view for (for a single one).
<fieldset>
<legend>Person</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
</fieldset>
In the Create page for the Account I include 2 of the partial views I created as below.
<div id="Person1">
@Html.Partial("_CreateAccountHolder" )
</div>
<div id="Person2">
@Html.Partial("_CreateAccountHolder")
</div>
When I look at what is posted back, it contains the values (Name and Age as the properties of Person) I put in the form values of the page and I have have the tow of them as expected:
CurrentBalance=19&Status=Closed&AccountOpenDate=12%2F12%2F2012&Name=mustafa&Age=20&Name=sofia&Age=20&AccountCloseDate=12%2F12%2F2012&AccountSuspensionDate=12%2F12%2F2012
But when I look at my create method on my controller I see the AccountHolder list as null. I tried with various signatures…
public ActionResult Create(Account personalaccount, Person [] accountHolders)
public ActionResult Create(Account personalaccount, List accountHolders)
If I only have one partial view of Person and have my controller like this, I can see the Person object bound correctly.
public ActionResult Create(Account personalaccount, Person accountHolder)
Any ideas as to where I am going wrong?
If I understand your scenario correctly one way to accomplish this is to use Editor Templates instead of partial views. I have a little write up about them here:
codenodes.wordpress.com – MVC3 Editor Templates
To create an Editor Template:
If you need to have individual divs around each Person then you can add these to your Editor Template. The good thing about Editor Templates is that you only need a single call to the template even if you have multiple Person objects in your list – no need to loop or anything like that as the template automatically renders each Person object. It also names the field correctly so it should post back something like this if for example you have 2 Person objects in your collection:
Here’s the code for your Editor Template: