【问题标题】:How to create a CRUD for multi-level child Model with ASP.Core & EF?如何使用 ASP.Core & EF 为多级子模型创建 CRUD?
【发布时间】:2019-06-26 11:49:41
【问题描述】:

我正在尝试创建一个可以编辑模型及其所有子模型的 CRUD,但每次父模型最终为空时,如何使用 ASP.Core 2.2 正确执行脚手架 CRUD ?

//Models

class Book {
    int IdBook {get; set;}
    string Name {getl set;}
    ICollection<Page> PageList {get; set;}
}

class Page {
    int IdPage {get; set;}
    string Name {get; set;}
    ICollection<Line> LineList {get; set;}
}

class Line{
     int IdLine {get;set;}
     string Content {get; set;} 
}

这是我的控制器

//Controller

public async Task<IActionResult> Edit(int? id)
{
    var book = _context.Book
                    .Include(b => b.PageList)
                    .ThenInclude(p => p.LineList)
                    .First();

    return View(book);
}

这就是我想要做的事情

@model Book

@Model.Name
@for(var indexPage = 0; indexPage < Model.PageList.Count; indexPage++)
{
    @Model.PageList[indexPage].Name
    @for(var indexLine = 0; indexLine < Model.PageList[indexPage].LineList.Count)
    {
        Html.EditorFor(x => x.PageList[indexPage].LineList[indexLine].Content)
    }
}

但是当我发布表单时,我只得到Book 的属性,而Book.PageListnull,这样做的正确方法是什么?有没有我会错过的教程?

更新

问题好像是类型,控制器接收到post参数 (我的代码有点不同,但都一样,书本就是例子)

【问题讨论】:

  • 如何在 ctrl 中创建书籍?它可能没有加载所有属性。
  • 刚刚更新问题
  • 视图加载正常,只有在表单帖子上,孩子们才会为空
  • 我觉得当我生成我的视图时延迟加载正在工作,但是当我发布到 saveChanges 时,延迟加载以某种方式被禁用并且子属性变为空,这可能吗?

标签: asp.net entity-framework razor asp.net-core


【解决方案1】:

您能否在处理您的请求的控制器上发布 action 方法的完整代码?

从您在 razor 视图页面上的代码中,在您迭代 PageList 的内部循环中,您不会增加您的 indexLine。这行不应该

@for(var indexLine = 0; indexLine &lt; Model.PageList[indexPage].LineList.Count)

@for(var indexLine = 0; indexLine &lt; Model.PageList[indexPage].LineList.Count, indexLine++)?

再次,在控制器上,如果 Request.Form 属性具有整个“假定”有效负载但模型绑定不起作用,请尝试使用 [FromBody] 注释注释 Submission 参数以清楚地通知 ASP.NET 绑定Submission 来自请求的 bofy - 就像这样

public async Task<IActionResult> Edit(int id, [FromBody] Submission submission) {}

查看这些小修复,如果您仍有任何问题,请告诉我

【讨论】:

  • 剃须刀的问题,是我的错,错误只在书中的例子中,而不是在我的实际代码中。对于绑定问题,我不得不做一些更改,但是使用[FromForm]标签,我能够检索到内容,谢谢,我不知道这个技巧!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
相关资源
最近更新 更多