Tân
Tân

Reputation: 1

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?

Upvotes: 36

Views: 31377

Answers (3)

alvescleiton
alvescleiton

Reputation: 1441

On .NET Core I use ViewDataDictionary with a parameter, like:

@Html.Partial("YourPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })

Upvotes: 9

Robert Massa
Robert Massa

Reputation: 4608

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 } })

Upvotes: 53

Ioannis Dontas
Ioannis Dontas

Reputation: 659

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 } }

Upvotes: 22

Related Questions