Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A view component named 'XX' could not be found

I am using aspnet 5 and MVC 6.

I have created a view component using the instructions in HERE but when I run my website I get an error

A view component named 'XX' could not be found. AT

@Component.Invoke("XX"))

Here is the structure of my project

namespace Test
{
public class XXViewComponent : ViewComponent
{
   public IViewComponentResult Invoke()
    {       
        return View();
    }
}

}

Then in the views folder I have Views/Assets/index.cshtml

<div>
    <div class="col-md-4">
        @Component.Invoke("XX"))
    </div>
</div>

The vc is in Views/Assets/Components/XX/default.cshtml

<div class="col-md-6" id="listOfCustomers">
    <table class="table table-condensed">
      <span> Test partial View</span>
    </table>
</div>
like image 861
Helen Araya Avatar asked Dec 18 '22 22:12

Helen Araya


2 Answers

I've had a similar issue. What helped me was the bottom section on the page you used yourself (Avoiding magic strings):

  • remove 'ViewComponent' suffix from the name of the class (and therefore the constructor) - you would then have:

    public class XX : ViewComponent
    
  • to use nameof when invoking the view component:

    @Component.Invoke(nameof(XX))
    
  • don't forget to use using of your view component in your main view (Views/Assets/index.cshtml) - in your case @using Test

This might both help you and keep the invoking of your component compile-time saved.

As Joe Audette pointed out, the views might be in an unusual location, but that would result in a different error message.

like image 107
Drakir Avatar answered Jan 14 '23 12:01

Drakir


I came across this question because I had a similar problem but where I want to dynamically load a particular view and needed to ensure that it exists before calling the View() method. This will let you know if the view exists or not. Not fully related with the question though, but hopefully will help people sent by google :)

this.ViewEngine.FindView(this.ViewContext, "test", false).Success
like image 32
Rui Lima Avatar answered Jan 14 '23 12:01

Rui Lima