ASP.NET MVC NHibernate - 将多选列表绑定到IList <t> </t>

时间:2015-02-04 14:40:37

标签: c# asp.net-mvc nhibernate

如何将多选下拉列表绑定到手动添加的中间表的列表属性?

public class Department
{
    public virtual int Id { get; set; }
    public virtual IList<Lam> Lams { get; set; }
}

public class Person
{
    public virtual int Id { get; set; }
    public virtual IList<Lam> Lams { get; set; }
}

public class Lam
{
    public virtual int Id { get; set; }
    public virtual Department Department { get; set; }
    public virtual Person Person { get; set; }
}

视图模型

public class DepartmentCreateEditViewModel
{
    public Department Department { get; set; }
    public IList<Person> Persons { get; set; }
}

的ActionResult

    public ActionResult Create()
    {
        // Get all Persons
        var persons = repositoryPerson.GetAll();

        // Create ViewModel
        var viewModel = new DepartmentCreateEditViewModel() { Department = new Department(), Persons = persons };

        // Display View
        return View(viewModel);
    }

创建视图

我尝试添加像这样的ListBox。

@Html.ListBoxFor(model => model.Department.Lams, new SelectList(Model.Persons, "Id", "Name"), new { @class = "form-controll" })

要保存我想要获取Department对象的对象

[HttpPost]
public ActionResult Create(Department department)

从下拉列表(与人员)到IList的绑定不起作用。我该怎么做?这甚至可能吗?


[编辑] Erik建议后的代码

创建ActionResult

[HttpPost]
public ActionResult Create(DepartmentCreateEditViewModel viewModelPostBack)

查看

@Html.ListBoxFor(model => model.Department.Lams, new MultiSelectList(Model.Persons, "Id", "Name"), new { @class = "form-controll" })

我得到了什么:

viewModelPostBack
{EmpLaceMgmt.ViewModels.DepartmentCreateEditViewModel}
    Department: {EmpLaceMgmt.Models.Department}
    Persons: null
viewModelPostBack.Department
{EmpLaceMgmt.Models.Department}
    Id: 0
    Lams: Count = 0

生成的HTML如下所示

<select class="form-controll" id="Department_Lams" multiple="multiple" name="Department.Lams">
    <option value="1">Example Person</option>
</select>

1 个答案:

答案 0 :(得分:1)

你有三个问题。首先,您尝试绑定到IList<T>,但这不起作用,因为模型绑定器不知道它应该创建哪种具体对象来满足...有许多对象支持{ {1}},哪一个?

其次,您需要在助手中使用IList<T>而不是MultiSelectList

第三,您回复的模型类型与创建页面时的模型类型不同。而那种类型的结构非常不同。在您创建网页的结构中,您的数据是使用SelectList的命名创建的(因为Department.Lams是ViewModel的属性)但在Post操作中需要Department模型其中,绑定器将寻找一个简称为Department的对象,而不是Lams

因此,将模型转换为使用具体类型(例如Department.Lams),然后回发到ViewModel而不是Department,并将部门从ViewModel中提取出来,最后将帮助程序更改为:< / p>

List<Lam>