I have a many-to-many relationship defined in my models among the following entities -
Diseases > Symptoms (One disease can have more than one symptom. One symptom may belong to more than one disease)
I am using a jQuery based Multiple Select Dropdown (Select2) to associate mutiple symptoms at the time of creating a disease entry.
I have got the Adding Disease Information correct so far. I am unable to get the Edit part. I have reviewed a couple of posts here but don't quite seem to get it correct as some of them deal with checkboxes rather than a dropdown.
Here is the code so far:
Model
public class Disease
{
public Disease()
{
this.Indications = new HashSet<App.Models.Indication.Indication>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int32 DiseaseID { get; set; }
[Required]
[Display(Name = "Disease")]
[StringLength(100)]
public string DiseaseName { get; set; }
public virtual ICollection<App.Models.Indication.Indication> Indications { get; set; }
}
public class DiseaseAddViewModel
{
public Disease Disease {get; set;}
public IEnumerable<SelectListItem> Indications { get; set; }
public Int32[] SelectedIndications { get; set; }
}
An excerpt from the view is as follows -
<div class="col-sm-9">
@Html.DropDownListFor(m => m.SelectedIndications, Model.Indications, new { @class="select2_demo_1 form-control", @multiple="multiple" })
</div>
Controller
[HttpGet]
public ActionResult Add()
{
var model = new DiseaseAddViewModel();
var allIndications = db.Indication.ToList();
model.Indications = allIndications.Select(o => new SelectListItem
{
Text = o.IndicationName,
Value = o.IndicationID.ToString()
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(DiseaseAddViewModel model)
{
if (ModelState.IsValid)
{
if (!db.Disease.Any(d => d.DiseaseName == model.Disease.DiseaseName))
{
Int32[] selectedIndications = model.SelectedIndications;
var Disease = new Disease { DiseaseName = model.Disease.DiseaseName };
AddIndications(Disease, selectedIndications);
db.Disease.Add(Disease);
db.SaveChanges();
TempData["SuccessMsg"] = "Disease information added successfully.";
}
else
{
TempData["ErrorMsg"] = "Disease name already exists in the database.";
}
return RedirectToAction("Index", "Diseases");
}
return View();
}
private void AddIndications(Disease disease, Int32[] assignedIndications)
{
for (int item = 0; item < assignedIndications.Length; item++)
{
var indication = new Indication();
indication.IndicationID = assignedIndications[item];
db.Indication.Attach(indication);
disease.Indications.Add(indication);
}
}
How do I code the Edit (Get and Post) so that the related indications are pre-populated in the dropdown and upon posting how do I manage the addition/removal of related entities?
Please feel free to suggest if there is a better way to do the Add functionality from above.
Many thanks!