1

我正在尝试将多个租户添加到 House 实体。我的错误是下拉框 (option.TenantID == Model.TenantID) 我不知道如何比较 int 和 Icollection。

模型

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>();
    }

}
}

控制器

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);
}

编辑视图

  @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>
 }

错误

Operator '==' cannot be applied to operands of type 'int' and     'System.Collections.Generic.ICollection<FlatSystem.Models.Tenants>'
4

1 回答 1

0

由于您在模型中有多个租户,也许您正在寻找一个ListBox(允许多项选择)。

@Html.ListBoxFor(model => model.TenantID, ((IEnumerable<FlatSystem.Models.Tenants>)ViewBag.TenantLookupList).Select(option => new SelectListItem
    {
        Text = (option == null) ? "None" : option.Firstname),
        Value = option.TenantID.ToString()
    }), "Choose...")

请注意,您不需要Selected显式设置属性,因为这是由模型确定的。您应该会看到Model.TenantID所选集合中的所有项目。


如果要设置所选项目,则必须使用Html.ListBox.

@Html.ListBox("MyListBox", ((IEnumerable<FlatSystem.Models.Tenants>)ViewBag.TenantLookupList).Select(option => new SelectListItem
{
    Text = (option == null) ? "None" : option.Firstname),
    Value = option.TenantID.ToString(),
    Selected = Model.TenantID.Any(tenant => tenant.ID == option.TenantID)
}), "Choose...")
于 2012-09-27T05:55:52.213 回答