Tân*_*Tân 15 asp.net asp.net-mvc asp.net-core
我的情况如下:
模型:
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; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public IActionResult Detail(string id)
{
ViewData["DbContext"] = _context; // DbContext
var model = ... // book model
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
视图:
详细视图:
@if (Model?.Count > 0)
{
var context = (ApplicationDbContext)ViewData["DbContext"];
IEnumerable<Comment> comments = context.Comments.Where(x => x.BookId == Model.Id);
@Html.Partial("_Comment", comments)
}
Run Code Online (Sandbox Code Playgroud)
评论局部视图:
@model IEnumerable<Comment>
@if (Model?.Count > 0)
{
<!-- display comments here... -->
}
<-- How to get "BookId" here if Model is null? -->
Run Code Online (Sandbox Code Playgroud)
我试过这个:
@Html.Partial("_Comment", comments, new ViewDataDictionary { { "BookId", Model.Id } })
Run Code Online (Sandbox Code Playgroud)
然后
@{
string bookid = ViewData["BookId"]?.ToString() ?? "";
}
@if (Model?.Count() > 0)
{
<!-- display comments here... -->
}
<div id="@bookid">
other implements...
</div>
Run Code Online (Sandbox Code Playgroud)
但是错误:
'ViewDataDictionary'不包含带0参数的构造函数
当我选择ViewDataDictionary
并按下时F12
,它会命中:
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public ViewDataDictionary(IModelMetadataProvider metadataProvider, ModelStateDictionary modelState);
}
Run Code Online (Sandbox Code Playgroud)
我不知道是什么IModelMetadataProvider
和ModelStateDictionary
?
我的目标:将模型comments
从视图发送Detail.cshtml
到部分视图_Comment.cshtml
,ViewDataDictionary
其中包含BookId
.
我的问题:我怎么能这样做?
Rob*_*ssa 19
另一种使用它的方法是ViewData
将当前视图传递给构造函数.这样ViewDataDictionary
,使用集合初始化程序放入的项目会扩展新的内容.
@Html.Partial("MyPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })
Run Code Online (Sandbox Code Playgroud)
使用以下代码创建ViewDataDictionary
new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()) { { "BookId", Model.Id } }
Run Code Online (Sandbox Code Playgroud)
在 .NET Core 上,我使用带有参数的 ViewDataDictionary,例如:
@Html.Partial("YourPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })
归档时间: |
|
查看次数: |
10828 次 |
最近记录: |