我的情况如下:

模型:

public class Book
{
    public string Id { get; set; }

    public string Name { get; set; }
}

public class Comment
{
    public string Id { get; set; }

    public string BookId { get; set; }

    public string Content { get; set; }
}

Controller :
public IActionResult Detail(string id)
{
    ViewData["DbContext"] = _context; // DbContext

    var model = ... // book model

    return View(model);
}

View :

详细 View :
@if (Model?.Count > 0)
{
    var context = (ApplicationDbContext)ViewData["DbContext"];
    IEnumerable<Comment> comments = context.Comments.Where(x => x.BookId == Model.Id);

    @Html.Partial("_Comment", comments)
}

评论部分 View :
@model IEnumerable<Comment>

@if (Model?.Count > 0)
{
    <!-- display comments here... -->
}

<-- How to get "BookId" here if Model is null? -->

我已经试过了:
@Html.Partial("_Comment", comments, new ViewDataDictionary { { "BookId", Model.Id } })

然后
@{
    string bookid = ViewData["BookId"]?.ToString() ?? "";
}

@if (Model?.Count() > 0)
{
    <!-- display comments here... -->
}

<div id="@bookid">
    other implements...
</div>

但是错误:



当我选择ViewDataDictionary并按F12时,它将显示为:
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
    public ViewDataDictionary(IModelMetadataProvider metadataProvider, ModelStateDictionary modelState);
}

我不知道IModelMetadataProviderModelStateDictionary是什么?

我的目标:使用包含commentsDetail.cshtml将模型_Comment.cshtml从 View ViewDataDictionary发送到部分 View BookId

我的问题:我该怎么做?

最佳答案

使用此方法的另一种方法是将当前 View 的ViewData传递给构造函数。这样,新的ViewDataDictionary就会扩展为您使用集合初始值设定项放入的项目。

@Html.Partial("MyPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })

10-07 13:48
查看更多