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?
Detail.cshtml. I have to refer many models:Book,BookDetail,UserProfile,Comment. It's so hard if you compress all of them to a model, then calling it in the view. Also, in asp.net core, there is no constructor for classApplicationDbContextwith 0 parameter by default. So, I cannot useusing (var db = new ApplicationDbContext){}in the View like mvc 5.Bookmodel should have aICollection<Comment>so all the comments are loaded when you get the book. And passing db context to the view is awful practice - you controller is responsible for getting the data as passing it to the viewstring UserNameproperty to display the nae of the user) Then in the GET method, initialize an instance of that view model and set its properties and pass the view model to the view.