Mixing Razor Views and Web Forms Master Pages

2019-07-16 08:19发布

问题:

I'm attempting to do what Scott Hanselman describes below:

http://www.hanselman.com/blog/MixingRazorViewsAndWebFormsMasterPagesWithASPNETMVC3.aspx

I have a Web Form user control with code behind that is called from the Web Form and Razor Master Pages that is not working in the Razor layout:

<div id="navtop">
    @{ Html.RenderPartial("~/Controls/MasterPageMenu.ascx"); }
</div>

The user control contains the following:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MasterPageMenu.ascx.cs" Inherits="Controls.MasterPageMenu" %>

I get the error: The view at '~/Controls/MasterPageMenu.ascx' must derive from ViewPage, ViewPage, ViewUserControl, or ViewUserControl.

What have I missed in getting this to work in the Razor view world?

回答1:

This should work, just make sure that your partial derives from ViewUserControl:

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl" 
%>

Remember that using server side controls in ASP.NET MVC is not something that's recommended even with the WebForms view engine and not something that you should even be attempting to do. In ASP.NET MVC you have layouts (master pages if you use WebForms view engine), views and partials. That's all. User controls belong to classic WebForms, not to ASP.NET MVC.