0

I have a PartialView that is working properly when called like this:

<div id="EmailAddresses">

    @foreach (FormEmailMessageEmailAddress toRecipient in Model.ToRecipients)
    {
        @Html.Partial("~/Views/FormEmailMessageEmailAddresses/_Edit.cshtml", toRecipient)    
    }

</div>

Next section of code, I have an Ajax call that is returning the Model and adding to the DOM:

<div class="form-group">
    <div class="col-md-10" style="float: right;">
        @Ajax.ActionLink(
                "Add",
                "AddNewEmailAddress",
                null,
                new { id = Model.Oid },
                new AjaxOptions
                {
                    HttpMethod = "GET",
                    InsertionMode = InsertionMode.InsertAfter,
                    UpdateTargetId = "EmailAddresses",
                },
                new { style = "btn btn-info" }
            )
    </div>
</div>

"~/Views/FormEmailMessageEmailAddresses/_Edit.cshtml" looks basically like this:

@model x.Models.Forms.Actions.FormEmailMessageEmailAddress

@using (Html.BeginCollectionItem(ViewData.TemplateInfo.HtmlFieldPrefix + ".ToRecipients"))
{
    @* Bunch of omitted code *@
}

When the PartialView is populated from database entries, the Html.BeginCollectionItem string looks similar to EmailMessages[997a1db6-6205-4118-90e4-11013d8d33db].ToRecipients[780bd8fa-4121-4d45-8fbc-35f4b8fd3086], however, when called from the Ajax function, it looks like .ToRecipients[222a5fa2-70d6-4cac-afbc-e865b0a753be].

Becuase thie Prefix is missing, the Controller doesn't see the new Collection.

The HtmlFieldPrefix doesn't have the information when using an Ajax call or something else that I have incorrect, please let me know your thoughts in pointing me towards a solution.

adiga
  • 34,372
  • 9
  • 61
  • 83
Derek
  • 653
  • 7
  • 20
  • Just `@using (Html.BeginCollectionItem("ToRecipients")) {` –  Sep 06 '17 at 01:32
  • `ToRecipients` is a List from `EmailMessages`, which is also a List within my root Model (`Form`, not outlined at the top of the first example). Removing `ViewData.TemplateInfo.HtmlFieldPrefix` doesn't allow the first part of my already working code to continue to work. `ToRecipients` List has a Count of 0. – Derek Sep 06 '17 at 01:40
  • What??? You code shows that `ToRecipients` is a collection property in your model so it needs to be as per the code in the first example which will generate inputs with `name=ToRecipients[].yourPropertyName` which will bind to your model. Are you saying that you have nested collections? - in which case you cannot use `BeginCollectionItem` –  Sep 06 '17 at 01:44
  • If you do have nested collections, then you can look at using [this extension method](http://www.joe-stevens.com/2011/06/06/editing-and-binding-nested-lists-with-asp-net-mvc-2/) –  Sep 06 '17 at 02:27

0 Answers0