Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ViewDataDictionary with Html.Partial in asp.net core?

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?

like image 254
Tân Avatar asked Nov 08 '16 06:11

Tân


People also ask

How do you use partial view in razor pages?

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.


2 Answers

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 } }) 
like image 97
Robert Massa Avatar answered Nov 11 '22 14:11

Robert Massa


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 } } 
like image 21
Ioannis Dontas Avatar answered Nov 11 '22 15:11

Ioannis Dontas