0

I am using MVC 5,C#6 and VS 2017. As part of a model I am using to populate an MVC form I have a collection of type Admission where the class Admission is defined as

public class Admission
{
    public DateTime AdmissionDate {get; set;}
    public YesNo EmergencyAdmission {get: set;}
    public DateTime DischargeDate {get; set;}
}

and YesNo is an enum. For simplification I have reduced the parent model to:

public class Patient
{
    public int PatientID {get; set;}
    public string PatientName {get; set;}
    public List<Admission> Admissions {get; set;}
}

Admissions can be added dynamically on the client side. When the model is instantiated there is a single empty admission. Within the form I have

@foreach (var item in Model.Patient.Admissions)
{
    Html.RenderPartial("Admission", item);
}

and in the partial view I then use:

 @Html.EditorFor(m => m.AdmissionDate)
 @Html.EditorFor(m => m.EmergencyAdmission)
 @Html.EditorFor(m => m.DischargeDate)

I have editor templates to handle the dates and the YesNo enum.

My question is that I do not know how to bind the model on post for the list of admissions. If I use Request.Form and write my own binder the items for the partial view are being posted as arrays the array structure is lost on Request.Form. The only solutions I have seen involve use fairly complex JavaScript/jQuery functions. I want to do as much as possible server side. If I can solve this part then I have a way of dynamically adding additional admissions.

Peter Smith
  • 5,528
  • 8
  • 51
  • 77
  • 1
    Your use of `RenderPartial()` means your not generating the correct `name` attributes (with the necessary prefix) for binding. Suggest you read [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) to understand how to generate forms controls for a collection –  May 24 '17 at 11:50
  • 1
    And for dynamically adding and deleting collection items, refer [here](https://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) and [here](https://stackoverflow.com/questions/40539321/a-partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892) –  May 24 '17 at 11:54
  • Can you add this as an answer so that I can accept it. – Peter Smith May 24 '17 at 12:17
  • 1
    I'll just dupe it –  May 24 '17 at 12:19

1 Answers1

0

Make an editor for Admission instead of a partial.

chris-crush-code
  • 1,114
  • 2
  • 8
  • 17