我的情况如下:
模型:
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); }
视图:
详细视图:
@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 } })
然后
@{ string bookid = ViewData["BookId"]?.ToString() ?? ""; } @if (Model?.Count() > 0) { <!-- display comments here... --> } <div id="@bookid"> other implements... </div>
但是错误:
‘ViewDataDictionary’ does not contain a constructor that takes 0
arguments
当我选择ViewDataDictionary并按F12时,它会命中:
namespace Microsoft.AspNetCore.Mvc.ViewFeatures { public ViewDataDictionary(IModelMetadataProvider MetadataProvider,ModelStateDictionary modelState); }
我不知道什么是IModelMetadataProvider和ModelStateDictionary?
我的目标:将视图Detail.cshtml中的模型注释发送到部分视图_Comment.cshtml,其中包含一个包含BookId的ViewDataDictionary.
我的问题:我怎么能这样做?