Thomas K
Thomas K

Reputation: 41

Asp.net core View components model binding

I'm looking for a way to invoke Model binder inside View component. I prefer to use build-in functionality from asp.net core, but this is only available inside controllers, not View Components itself. Any way to resolve that problem?

Upvotes: 4

Views: 4834

Answers (4)

Jason Shave
Jason Shave

Reputation: 2672

I solved this in my project by using ASP.NET Core's dependency injection to insert my singleton directly into a Razor view.

The code snippet below uses the SignalR JavaScript library to send a notification to the browser if something comes in while they're watching the screen. When the page first loads though, I want to display the notification count in a CSS "bell" image so I get the count from the "singleton" object registered in Startup.cs. I use the List<Notification> object in my back-end code to add new notifications to the single instance object as well as sending the signal to the browser. DI worked great in this case to solve the model binding need.

Startup.cs

services.AddSingleton<List<Notification>>();

NotificationComponent.cshtml

@using PWVault.Service.Notification //optional as you can specify the full namespace instead below
@inject List<Notification> Notifications //this is my registered Singleton from Startup.cs

<link rel="stylesheet" href="~/css/NotificationBadge.css" />

<div class="notificationContainer">
    <div class="notification" data-toggle="modal" data-target="#notificationModal"> 
</div>
    <label hidden="hidden" id="notificationCount">@Notifications.Count</label>
</div>

@*modal window*@
@await Html.PartialAsync("_NotificationDetailModal")

<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/NotificationHub.js"></script>

Upvotes: 0

Francesco Venturini
Francesco Venturini

Reputation: 115

You can even use TagHelper

 <vc:my-component model="@(Model)"></vc:my-component>

and inside your ViewComponent

public async Task<IViewComponentResult> InvokeAsync(MyModel model)

This is not present inside the official guide

Upvotes: 1

Lukasz Mk
Lukasz Mk

Reputation: 7350

According to View Components documentation:

View Components don’t use model binding, and only depend on the data you provide when calling into it.


However, you could pass model as an object/parameter into your ViewComponent:

@await Component.InvokeAsync("PriorityList", MyModel)

or

@await Component.InvokeAsync("PriorityList", new { maxPriority = 2, isDone = false })


What do you want to achieve?

Upvotes: 4

Joseph Woodward
Joseph Woodward

Reputation: 9281

As far as I'm aware, this is not possible. The model binding occurs further up in the framework's lifecycle before the controller action is invoked.

I would be really interested in seeing some code as to why you need to do this to see if there are any other potential solutions that wouldn't involve model binding.

Upvotes: 3

Related Questions