如何编辑和保存Asp MVC中的一对多关系对象

时间:2016-10-12 16:09:23

标签: c# asp.net-mvc

我不明白该怎么做。 我有三个模特。

我的供应商模型

public class Supplier
{
    [Key]
    public int SupplierID { set; get; }
    public string Name { set; get; }
    public virtual ICollection<Manager> Managers { get; set; }
}

供应商有很多经理。

我的经理模特

public class Manager
{
    [Key]
    public int ManagerID { set; get; 
    public string Name { set; get; }
    public virtual ICollection<Supplier> Suppliers { get; set; }
    public virtual ICollection<Phone> Phones { get; set; }
}

经理有很多电话号码

手机型号

public class Phone
{
    [Key]
    public int PhoneID { set; get; }
    public string PhoneNumber { set; get; }
    public virtual ICollection<Manager> Manager { get; set; }
}

然后我在项目中创建ModelView

public class SupplierView
{
    public Supplier Supplier { get; set; }
    public IEnumerable<Manager> Managers { get; set; }
    public string Manger_Name { get; set; }
    public string Manager_New_Phone { get; set; }
}

在控制器中,我创建模型并将模型传递给局部视图。

public ActionResult Edit(int id)
{
    var supplier = db.Suppliers.Find(id);
    var model = new SupplierView
    {
        Supplier = supplier
    };

    return PartialView("_Supplier_Edit", model);
}

编辑视图效果很好,显示有关供应商的所有信息。

@using (Html.BeginForm("Save", "Supplier", FormMethod.Post, new { @class = "ui form" }))
{
    @Html.AntiForgeryToken()
        <div class="two fields">
        <div class="field">
            @Html.LabelFor(m => Model.Supplier.Name)
        </div>
    </div>
    foreach (var manager in Model.Supplier.Managers)
    {
        <div class="two fields">
            <div class="field">
                <label>Manager Name</label>

                @if (manager.Name.Any())
                {
                    @Html.TextBoxFor(m => manager.Name)
                }
                else
                {
                    @Html.TextBoxFor(m => m.Manger_Name)
                }
            </div>
            <div class="field">
                <label>Phone</label>
                @if (manager.Phones.Any())
                {
                    foreach (var phones in manager.Phones)
                    {
                        @Html.TextBoxFor(m => phones.PhoneNumber)
                    }
                }
                else
                {
                    @Html.TextBoxFor(m => m.Manager_New_Phone)
                }
            </div>
        </div>
    }
}

我不知道如何为该表单保存控制器。

详情控制器

[HttpPost]
public ActionResult Details(int id)
{
    var supplier = db.Suppliers.Find(id);
    if (supplier == null)
    {
        return HttpNotFound();
    }
    var model = new SupplierView
    {
         Supplier = supplier
    };
    return PartialView("_Supplier_Details", model);
}

0 个答案:

没有答案