MVC 4编辑控制器/查看多对多关系和复选框

时间:2013-07-23 14:08:29

标签: c# entity-framework asp.net-mvc-4 checkbox many-to-many

我正在使用ASP.NET MVC 4和Entity Framework,我正在寻找一些方法来创建多个关系和复选框来自我的数据库,用于创建/编辑控制器和视图,我已经找到了@的答案Slauma回答了MVC 4 - Many-to-Many relation and checkboxes中的Create,但是,我真的很想看看这是如何扩展到编辑和删除功能的,以及此解决方案中的其他一些合作伙伴。有人可以说明如何在Edit控制器方法中填充ClassificationSelectViewModel以获取“已选中”和“未选中”值吗?这是一个Matt Flowers问题,也将解决我的问题。

1 个答案:

答案 0 :(得分:10)

以下是this answer的续篇,其中描述了Create实体SubscriptionCompany.之间具有多对多关系的模型的GET和POST操作Edit动作的过程如何做到(除了我可能不会将所有EF代码放入控制器动作但将其提取到扩展和服务方法中):

CompanySelectViewModel保持不变:

public class CompanySelectViewModel
{
    public int CompanyId { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

SubscriptionEditViewModelSubscriptionCreateViewModel加上Subscription的关键属性:

public class SubscriptionEditViewModel
{
    public int Id { get; set; }
    public int Amount { get; set; }
    public IEnumerable<CompanySelectViewModel> Companies { get; set; }
}

GET操作可能如下所示:

public ActionResult Edit(int id)
{
    // Load the subscription with the requested id from the DB
    // together with its current related companies (only their Ids)
    var data = _context.Subscriptions
        .Where(s => s.SubscriptionId == id)
        .Select(s => new
        {
            ViewModel = new SubscriptionEditViewModel
            {
                Id = s.SubscriptionId
                Amount = s.Amount
            },
            CompanyIds = s.Companies.Select(c => c.CompanyId)
        })
        .SingleOrDefault();

    if (data == null)
        return HttpNotFound();

    // Load all companies from the DB
    data.ViewModel.Companies = _context.Companies
        .Select(c => new CompanySelectViewModel
        {
            CompanyId = c.CompanyId,
            Name = c.Name
        })
        .ToList();

    // Set IsSelected flag: true (= checkbox checked) if the company
    // is already related with the subscription; false, if not
    foreach (var c in data.ViewModel.Companies)
        c.IsSelected = data.CompanyIds.Contains(c.CompanyId);

    return View(data.ViewModel);
}

Edit视图是Create视图以及Subscription的关键属性Id的隐藏字段:

@model SubscriptionEditViewModel

@using (Html.BeginForm()) {

    @Html.HiddenFor(model => model.Id)
    @Html.EditorFor(model => model.Amount)

    @Html.EditorFor(model => model.Companies)

    <input type="submit" value="Save changes" />
    @Html.ActionLink("Cancel", "Index")
}

选择公司的编辑器模板保持不变:

@model CompanySelectViewModel

@Html.HiddenFor(model => model.CompanyId)
@Html.HiddenFor(model => model.Name)

@Html.LabelFor(model => model.IsSelected, Model.Name)
@Html.EditorFor(model => model.IsSelected)

POST动作可能是这样的:

[HttpPost]
public ActionResult Edit(SubscriptionEditViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var subscription = _context.Subscriptions.Include(s => s.Companies)
            .SingleOrDefault(s => s.SubscriptionId == viewModel.Id);

        if (subscription != null)
        {
            // Update scalar properties like "Amount"
            subscription.Amount = viewModel.Amount;
            // or more generic for multiple scalar properties
            // _context.Entry(subscription).CurrentValues.SetValues(viewModel);
            // But this will work only if you use the same key property name
            // in ViewModel and entity

            foreach (var company in viewModel.Companies)
            {
                if (company.IsSelected)
                {
                    if (!subscription.Companies.Any(
                        c => c.CompanyId == company.CompanyId))
                    {
                        // if company is selected but not yet
                        // related in DB, add relationship
                        var addedCompany = new Company
                            { CompanyId = company.CompanyId };
                        _context.Companies.Attach(addedCompany);
                        subscription.Companies.Add(addedCompany);
                    }
                }
                else
                {
                    var removedCompany = subscription.Companies
                       .SingleOrDefault(c => c.CompanyId == company.CompanyId);
                    if (removedCompany != null)
                        // if company is not selected but currently
                        // related in DB, remove relationship
                        subscription.Companies.Remove(removedCompany);
                }
            }

            _context.SaveChanges();
        }

        return RedirectToAction("Index");
    }

    return View(viewModel);
}

Delete行动不那么困难。在GET操作中,您可以加载一些订阅属性以显示在删除确认视图中:

public ActionResult Delete(int id)
{
    // Load subscription with given id from DB
    // and populate a `SubscriptionDeleteViewModel`.
    // It does not need to contain the related companies

    return View(viewModel);
}

然后在POST操作中加载实体并将其删除。不需要包含公司,因为在多对多关系(通常)链接表上的级联删除已启用,因此数据库将负责删除与父Subscription一起的链接条目:

[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirm(int id)
{
    var subscription = _context.Subscriptions.Find(id);
    if (subscription != null)
        _context.Subscriptions.Remove(subscription);

    return RedirectToAction("Index");
}