我的情况如下:
型号:
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'不包含带0的构造函数 参数
当我选择ViewDataDictionary
并按F12
时,会点击:
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public ViewDataDictionary(IModelMetadataProvider metadataProvider, ModelStateDictionary modelState);
}
我不知道IModelMetadataProvider
和ModelStateDictionary
是什么?
我的目标:将视图comments
中的模型Detail.cshtml
发送到部分视图_Comment.cshtml
,其中ViewDataDictionary
包含BookId
。
我的问题:我该怎么做?
答案 0 :(得分:15)
另一种使用方法是将当前视图的ViewData
传递给构造函数。这样,新的ViewDataDictionary
将使用您使用集合初始化程序放入的项目进行扩展。
@Html.Partial("MyPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })
答案 1 :(得分:7)
使用以下代码创建ViewDataDictionary
new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()) { { "BookId", Model.Id } }
答案 2 :(得分:0)
在.NET Core上,我使用带有参数的ViewDataDictionary,例如:
@ Html.Partial(“ YourPartial”,新的ViewDataDictionary(ViewData){{“ BookId”,Model.Id}})