我的案例是这样的:
Model:
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; }
}
控制器:
public IActionResult Detail(string id)
{
ViewData["DbContext"] = _context; // DbContext
var model = ... // book model
return View(model);
}
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)
}
评论部分视图:
@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 } })
Then
@{
string bookid = ViewData["BookId"]?.ToString() ?? "";
}
@if (Model?.Count() > 0)
{
<!-- display comments here... -->
}
<div id="@bookid">
other implements...
</div>
但错误:
“ViewDataDictionary”不包含采用 0 的构造函数
论点
当我选择ViewDataDictionary
并按F12
,它会达到:
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public ViewDataDictionary(IModelMetadataProvider metadataProvider, ModelStateDictionary modelState);
}
我不知道是什么IModelMetadataProvider
and ModelStateDictionary
?
我的目标:发送模型comments
从视图Detail.cshtml
到部分视图_Comment.cshtml
with a ViewDataDictionary
其中包含BookId
.
我的问题:我该怎么做?