【问题标题】:Allow user to edit list items in MVC?允许用户在 MVC 中编辑列表项?
【发布时间】:2017-09-24 11:08:27
【问题描述】:

我正在使用 Entity Framework Core 构建一个简单的 Web 应用程序。对于这个应用程序,我创建了一个名为 Company 的模型,其中包括基本业务信息 + 联系人列表(销售代表)。

这是我的模型:

public class Company
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public string Promo { get; set; } 
    public virtual List<Contact> Contacts { get; set; }       
}

public class Contact
{
    [Key]
    public int ContactID { get; set; }
    [ForeignKey("Company")]
    public int CompanyID { get; set; }
    public virtual Company Company { get; set; }
    public string ContactName { get; set; }
    public string ContactNumber { get; set; }
}

这是控制器的 index() 方法:

// GET: Companies
    public async Task<IActionResult> Index()
    {
        List<Company> viewModelData = await _context.Companies
            .Include(c => c.Contacts)
            .ToListAsync();
        return View(viewModelData);
    }

编辑方法:

 // GET: Companies/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var company = await _context.Companies
                .Include(v => v.Contacts)
                .FirstOrDefaultAsync(m => m.ID == id);
            if (company == null)
            {
                return NotFound();
            }
            return View(company);
        }

        // POST: Companies/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int? id, [Bind("ID,Name,Promo,Contacts")] Company company)
        {
            if (id == null)
            {
                return NotFound();
            }

            var companyToUpdate = await _context.Companies
                .Include(v => v.Contacts)
                .FirstOrDefaultAsync(m => m.ID == id);
            if (await TryUpdateModelAsync<Company>(
                companyToUpdate,
                "",
                i => i.Name, i => i.Promo, i => i.Contacts
                )) { 
                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateException /* ex */)
                {
                    //Log the error (uncomment ex variable name and write a log.)
                    ModelState.AddModelError("", "Unable to save changes. " +
                        "Try again, and if the problem persists, " +
                        "see your system administrator.");
                }
            return RedirectToAction("Index");
        }
         return View(companyToUpdate);
    }

这是不正确的,因为代码只允许我编辑公司信息。如何修改代码以便我可以在同一个编辑视图中同时编辑公司及其联系人?

【问题讨论】:

  • 我从来没有真正使用过TryUpdateModel,所以很遗憾我不能对此发表评论,但是我可以建议使用视图模型而不是实际的 Dto,然后从 POST 映射视图模型到 Dto - 或使用 AutoMapper 来处理这些映射。然后你只需要在映射后使用_context.Companies.Update(companyToUpdate);,然后保存。

标签: asp.net asp.net-mvc visual-studio entity-framework


【解决方案1】:

如果您只是想更新值,那么您可以像这样显式地更新它们。还建议使用视图模型,但这归结为好与坏的做法。这省略了异常处理,仅作为如何映射这些值的示例,您必须修改控制器的其余部分才能直接使用 CompanyEditViewModel

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int? id, [Bind("ID,Name,Promo,Contacts")] CompanyEditViewModel company)
{
    if (!ModelState.IsValid)
        return RedirectToAction("Index");

    var companyToUpdate = await _context.Companies
        .Include(v => v.Contacts)
        .FirstOrDefaultAsync(m => m.ID == id);

    // Assign the new values
    companyToUpdate.Name = company.Name;
    companyToUpdate.Promo = company.Promo;
    companyToUpdate.Contacts = company.Contacts?.ToList();

    // Update and save
    _context.Companies.Update(companyToUpdate);
    await _context.SaveChangesAsync();

    return View(companyToUpdate);
}

public class Company
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Promo { get; set; } // Yes or No field
    public List<Contact> Contacts { get; set; }

    public class Contact
    {
        [Key]
        public int ContactID { get; set; }

        public int CompanyID { get; set; }
        public string ContactName { get; set; }
        public string ContactNumber { get; set; }
    }
}

// The View Model contains the Company details which were modified
// The first Edit method will have to be updated to bind this View Model to the view
public class CompanyEditViewModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Promo { get; set; }
    public IList<Company.Contact> Contacts { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 2021-06-19
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多