Ciao a tutti e buon anno,
ho creato una view che visualizza tutti i contatti di un cliente tramite una property not mapped (Contacts) tramite un editorTemplate. I dati caricati provengono da una navigation property (CustomerContacts).
I valori in visualizzazione vengono caricati correttamente, però se vengono modificati oppure eliminati nel momento in cui si esegue il post per il salvataggio dei dati questi non sono valorizzati all'interno della entity.
Come potrei riuscire a salvare queste informazioni?
Di seguito riporto il codice:
Model Customer.cs
[Table("Customer")]
public class Customer : BaseEntity
{
...
public virtual ICollection<CustomerContact> CustomerContacts { get; set; }
[NotMapped]
public virtual ICollection<Contact> Contacts
{
get
{
ICollection<Contact> contacts = new List<Contact>();
ApplicationDbContext db = new ApplicationDbContext();
foreach (CustomerContact customerContact in CustomerContacts)
{
if (customerContact.ContactId > 0 && customerContact.CustomerId > 0)
contacts.Add(db.Contacts.First(c => c.Id.Equals(customerContact.ContactId)));
}
return contacts;
}
set
{
Contacts.Add(new Contact());
}
}
}
View Edit.cshtml (porzione di codice)
...
<!-- Start portlet contact information -->
<div class="col-md-6">
<div class="portlet box red-flamingo">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-phone"></i>
Contatti
</div>
<div class="tools">
<a class="collapse" href="" data-original-title="" title=""> </a>
<a class="fullscreen" href="" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<div class="form-horizontal mt-repeater">
<div class="form-body">
<div id="contacts">
@Html.EditorFor(model => model.Contacts)
</div>
<div class="row">
<div class="col-md-12" style="padding-right: 40px;">
<div class="pull-right">
<a href="javascript:;" data-repeater-create class="btn btn-success btn-icon-only red-flamingo mt-repeater-add">
<i class="fa fa-plus"></i>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End portlet contact information -->
...
EditorTemplate Contact.cshtml
<div class="contact">
<div class="form-body" style="padding-top: 0px;">
<div data-repeater-list="group-a">
<div data-repeater-item class="mt-repeater-item">
<!-- jQuery Repeater Container -->
<div class="row">
<div class="col-md-4">
<div class="input-group">
<div class="mt-repeater-input">
<label class="control-label"> </label>
@Html.DropDownList("Type", (List<SelectListItem>)@ViewBag.ContactType, ViewUtil.OPTION_LABEL, new { @class = "form-control" })
</div>
</div>
</div>
<div class="col-md-8">
<div class="input-group">
<div class="mt-repeater-input">
<label class="control-label"> </label>
@if (ContactType.EMAIL.Equals(Model.Type))
{
@Html.EditorFor(model => model.CompleteEmail, new { htmlAttributes = new { @class = "form-control", placeholder = "Inserisci contatto", type = "text" } })
}
else
{
@Html.EditorFor(model => model.Value, new { htmlAttributes = new { @class = "form-control", placeholder = "Inserisci contatto", type = "text" } })
}
</div>
</div>
</div>
</div>
<div class="mt-repeater-input">
<a href="javascript:;" data-repeater-delete class="btn btn-danger mt-repeater-delete">
<i class="fa fa-close"></i> Delete
</a>
</div>
</div>
</div>
</div>
</div>
Controller CustomersController.cs
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,Type,LastName,FirstName,InsertDate,TaxCode,Gender,AssumptionDate,ResidenceDate,Note,BirthDate,CountryEntryDate,AcceptPrivacy,Attribute1,DomicileAddress,ResidenceAddress,UpdateDate,ContractTypeId,CompanyId,NationalityId,ImageId,SourceId,SourcePracticeId,SubAgentId,SubStatusId,UserId,Contacts")] Customer customer)
{
if (ModelState.IsValid)
{
try
{
db.Entry(customer).State = EntityState.Modified;
customer.UserId = Convert.ToInt64(currentUserId);
await db.SaveChangesAsync();
}
catch (Exception /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
return RedirectToAction("Index");
}
return RedirectToAction("Edit", customer.Id);
}
I risultato finale nella pagina è il seguente:
LINKCon i pulsanti "Delete" e "+" si aggiungo o si eliminano i contatti dalla form, e solo al momento del salvataggio questi vengono riportati nel database.
Grazie
Ciao
Enrico