允许用户编辑MVC中的列表项目? [英] Allow user to edit list items in MVC?

查看:105
本文介绍了允许用户编辑MVC中的列表项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架核心构建一个简单的网络应用程序。对于这个应用程序,我创建了一个名为公司的模型,其中包含基本业务信息+联系人列表(销售代表)。

I'm using Entity Framework Core to build a simple web app. For this app, I've created a model called Company that includes basic business info + a list of contacts (sales reps).

这是我的模型:

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()方法:

Here's the controller's index() method:

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

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

This is not correct since the code only allows me to edit Company info. How do I modify the code so that I can edit both Company & its contacts on the same edit view?

推荐答案

如果您纯粹希望更新值,那么您可以显式更新它们所以。还建议一个视图模型,但这归功于对不好的做法。这省略了异常处理,仅作为如何映射这些值的示例,您必须修改控制器的剩余部分直接与 CompanyEditViewModel

If you're purely looking to update values, then you can explicitly update them like so. A View Model is also recommended but this comes down to good vs bad practice. This omits the exception handling and serves only as an example of how to map these values, you'll have to modify the remainder of your controller to work directly with the 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; }
}

这篇关于允许用户编辑MVC中的列表项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆