ASP.Net6.0生成的编辑页面丢失了外键对象的引用。
创始人
2024-09-17 04:30:36
0

在生成的编辑页面的控制器中,需要手动加载外键对象并绑定到视图模型中,以便在提交表单时可以正确地保存它们。

例如,在以下示例代码中,外键对象是“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

相关内容

热门资讯

黑科技科技(wepoke智能a... 黑科技科技(wepoke智能ai)wepower使用说明书(wepOkE)素来是真的有挂(确实有挂)...
黑科技模拟器(wepoke智能... WePoker透视辅助工具核心要点解析‌,黑科技模拟器(wepoke智能ai)wepoke是机器发牌...
黑科技脚本(wepokeai代... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游戏中打牌都...
黑科技辅助挂(wepoke真的... 黑科技辅助挂(wepoke真的有挂)wepoke 软件(wEPOKE)固有真的有挂(有挂猫腻)-哔哩...
黑科技辅助挂(wepoke黑科... 黑科技辅助挂(wepoke黑科技)wepoke软件透明挂演示(wEpOke)一直真的有挂(真的有挂)...
黑科技app(wepoke真的... 此外,数据分析德州()辅助神器app还具备辅助透视行为开挂功能,通过对客户透明挂的深入研究,你可以了...
黑科技智能ai(wepoke辅... 黑科技智能ai(wepoke辅助插件)wepoke软件透明(WEPOke)先前是有挂(果真有挂)-哔...
黑科技模拟器(wepoke透明... 黑科技模拟器(wepoke透明黑科技)wepoke德州扑克用ai代打(WEPOKE)最初存在有挂(有...
黑科技插件(wepoke辅助插... 黑科技插件(wepoke辅助插件)wepoke软件透明(WEPOke)从来是真的有挂(有挂解惑)-哔...
黑科技美元局(wepoke智能... 黑科技美元局(wepoke智能ai)wepoke辅助真的假的(wepoKE)原先真的有挂(竟然有挂)...