ASP.NET MVC Core 2:如何避免视图组件使用与父视图相同的模型?
Hey there, let's break down why you're getting that InvalidOperationException and how to fix it quickly.
The Root Cause
When you render a view component without explicitly passing a model to it, ASP.NET Core defaults to using the parent view's model as the component's model. In your scenario:
- Parent view uses
@model IEnumerable<Filters> - Your
MyFiltercomponent expects@model Filters
So when you call <vc:my-filter/> without a model, it tries to pass the parent's IEnumerable<Filters> to the component, which doesn't match the required type—hence the error.
Quick Fixes
1. Explicitly Pass an Empty Model in the Parent View
The simplest fix is to pass a new instance of Filters directly when invoking the component. This ensures it gets the correct type, even if it's an empty object:
<vc:my-filter model="@new Filters()" />
2. Set a Default Model in the View Component Class
If you don't want to add the model parameter everywhere you use the component, you can handle it in the component's code. Just default the model to a new Filters instance if it's null:
public class MyFilterViewComponent : ViewComponent { public IViewComponentResult Invoke(Filters model = null) { // Use an empty Filters instance if no model is provided var filterModel = model ?? new Filters(); return View(filterModel); } }
Now you can keep using <vc:my-filter/> in your parent view—no extra parameters needed. The component will automatically use a valid Filters object instead of falling back to the parent's model.
Pro Tip
Always be explicit about the model your view component receives. It makes your code easier to read and avoids these kinds of unexpected inheritance issues. If you need to handle null states in the component's view, you can add checks there, but providing a default empty instance is usually cleaner.
内容的提问来源于stack exchange,提问作者Daniel Santos

