简体   繁体   中英

ASP.NET MVC 3 partial view not found

I have following problem. In my solution I have 2 controllers: Home and Account. Everything works so far. But when I add [Authorize] above HomeController eg

[Authorize]
public class HomeController : Controller
{
...

I get

System.InvalidOperationException: The partial view 'Repository' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Account/Repository.aspx
~/Views/Account/Repository.ascx
~/Views/Shared/Repository.aspx
~/Views/Shared/Repository.ascx
~/Views/Account/Repository.cshtml
~/Views/Account/Repository.vbhtml
~/Views/Shared/Repository.cshtml
~/Views/Shared/Repository.vbhtml

Partial view Repository is inside HomeController so therefore its View is in ~/Views/Home/Repository.cshtml, but it's seacrhed in Shared or Account folders. As I said, if there is no [Authorize] above HomeController class, everything works as expected.

The code where error occurs is in _Layout.cshtml

@Html.Partial("Repository")

Thanks for help.

_Layout.cshtml is the master page for the entire application. What's happening is your home controller is looking for an authenticated user, finding that the user is not authenticated and redirecting to the login action in the Account controller. That action is then rendering its view which uses the _Layout.cshtml master page which wants to render the partial view but can't find it, because it's not in the Account folder.

Short answer: Partial views in your master page should be located in the ~/Views/Shared directory. Or move that partial call to a page that only gets run in the Home controller context.

Also, Check the following: Make sure the output type is set to content for the page in question. This was pointed out to me by a peer, Joe F. For whatever reason sometimes the output does not get set correctly. Thus, when you promote your app the cshtml file will not be copied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM