在生成的编辑页面的控制器中,需要手动加载外键对象并绑定到视图模型中,以便在提交表单时可以正确地保存它们。
例如,在以下示例代码中,外键对象是“Category”,并且“Product”模型中具有“CategoryId”属性,该属性用于将其与“Category”模型关联。对于编辑操作,需要通过类似下面的代码来加载外键对象:
// GET: Products/Edit/5
public async Task Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
// Load associated Category object
ViewData["CategoryId"] = new SelectList(_context.Categories, "CategoryId", "Name", product.CategoryId);
return View(product);
}
在上面的代码中,使用“SelectList”类创建“CategoryId”属性的“ViewData”对象,并使用“_context.Categories”获取所有类别,并将其绑定到下拉列表中。
接下来,在编辑操作的Post方法中,需要将外键对象的值从表单中读取并设置到模型对象中,以便可以正确保存它们。以下代码是一个例子:
// POST: Products/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?linkid=2145215.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Edit(int id, [Bind("ProductId,Name,Description,Price,CategoryId")] Product product)
{
if (id != product.ProductId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
// Set associated Category object
product.Category = await _context.Categories.FindAsync(product.CategoryId);
_context.Update(product);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(product.Product