My case looks like this:
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; } }
Controller:
public IActionResult Detail(string id) { ViewData["DbContext"] = _context; // DbContext var model = ... // book model return View(model); }
View:
Detail 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) }
Comment partial view:
@model IEnumerable<Comment> @if (Model?.Count > 0) { <!-- display comments here... --> } <-- How to get "BookId" here if Model is null? -->
I've tried this:
@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>
But error:
'ViewDataDictionary' does not contain a constructor that takes 0 arguments
When I select ViewDataDictionary
and press F12
, it hits to:
namespace Microsoft.AspNetCore.Mvc.ViewFeatures { public ViewDataDictionary(IModelMetadataProvider metadataProvider, ModelStateDictionary modelState); }
I don't know what are IModelMetadataProvider
and ModelStateDictionary
?
My goal: Send model comments
from view Detail.cshtml
to partial view _Comment.cshtml
with a ViewDataDictionary
which contains BookId
.
My question: How can I do that?
A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.
Another way to use this is to pass the ViewData
of the current view into the constructor. That way the new ViewDataDictionary
gets extended with the items you put in using the collection initializer.
@Html.Partial("MyPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })
Use the following code to create a ViewDataDictionary
new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()) { { "BookId", Model.Id } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With