I’m trying to add multiple Tenants to the House entity.
My Error is with the drop down box (option.TenantID == Model.TenantID)
I don’t know how to compare an int and Icollection.
Model
namespace FlatSystem.Models
{
[Table("House")]
public class House
{
[Key]
public int HouseID { get; set; }
public virtual ICollection<Tenants> TenantID { get; set; }
public House() {
TenantID = new HashSet<Tenants>();
}
}
}
Controller
public ActionResult Edit(int id)
{
ViewBag.TenantLookupList = TenantGR.All;
return View(GR.Find(id));
}
//
// POST: /House/Edit/5
[HttpPost]
public ActionResult Edit(House house)
{
if (ModelState.IsValid)
{
GR.InsertOrUpdate(house);
GR.Save();
return RedirectToAction("Index");
}
return View(house);
}
Edit View
@using (Html.BeginForm("AddRole", "Role", new { houseId = @Model.HouseID }))
{
<table>
<tr>
<td>Select to Add Item</td>
<td>
<div class="editor-field">
@Html.DropDownListFor(model => model.TenantID, ((IEnumerable<FlatSystem.Models.Tenants>)ViewBag.TenantLookupList).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Firstname),
Value = option.TenantID.ToString(),
Selected = (Model != null) && (option.TenantID == Model.TenantID) <<----Error
}), "Choose...")
</div>
</td>
<td><input type="submit" value="Add" /></td>
</tr>
</table>
}
Error
Operator '==' cannot be applied to operands of type 'int' and 'System.Collections.Generic.ICollection<FlatSystem.Models.Tenants>'
Since you have multiple tenants in the Model, maybe you’re looking for a
ListBox(which allows multiple selection).Note that you don’t need to set the
Selectedproperty explicitly, as that is determined by the model. You should see all the items in theModel.TenantIDcollection selected.If you want to set the selected items, then you have to use
Html.ListBox.