WebForm混合MVC

 WebForm混合MVC

WebForm模拟MVC

参考文章地址:https://blog.csdn.net/cownew/article/details/50400933

1、创建WebForm项目

2、新建AddView.aspx页面

删除AddView.aspx.csAddView.aspx.designer.cs两个文件

 

AddView.aspx页面内容如下:

 

<%@ Page Language="C#" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <%dynamic viewBag = Context.Items["ViewBag"]; %>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>加法计算器</title>
</head>
<body>
    <form id="form1">
        <input type="hidden" name="action" value="addSubmit" />
        <input type="text" name="i1" value="<%=viewBag.i1 %>" />+<input type="text" name="i2" value="<%=viewBag.i2%>" />
        <input type="submit" value="=" /><input type="text" value="<%=viewBag.i3 %>" />
    </form>
</body>
</html>

 

 

3、创建AddHandler.ashx一般处理程序

用来充当控制器的作用,C#代码如下:

 

public void ProcessRequest(HttpContext context)
        {
            string action = context.Request["action"];
            dynamic viewBag = new System.Dynamic.ExpandoObject();
            if (string.IsNullOrEmpty(action))
            {
                viewBag.i1 = "";
                viewBag.i2 = "";
                viewBag.i3 = "";
            }
            else if (action == "addSubmit")
            {
                int i1 = Convert.ToInt32(context.Request["i1"]);
                int i2 = Convert.ToInt32(context.Request["i2"]);
                int i3 = i1 + i2;
                viewBag.i1 = i1;
                viewBag.i2 = i2;
                viewBag.i3 = i3;
            }
            context.Items["ViewBag"] = viewBag;
            context.Server.Transfer("AddView.aspx");
            //---------------------
            //作者:cownew
            //来源:CSDN
            //原文:https://blog.csdn.net/cownew/article/details/50400933 
            //版权声明:本文为博主原创文章,转载请附上博文链接!
        }

 

4、运行项目

 

在浏览器端输入

http://localhost:6951/AddHandler.ashx?action=addSubmit

或者http://localhost:6951/AddHandler.ashx?action=addSubmit&i1=3&i2=5

 

这样就实现了MVC页面加载功能啦。

 

=====================================================================

 

WebForm项目嵌套MVC项目

参考文章地址:http://www.cnblogs.com/encoding/articles/3556046.html

1、WebForm项目添加引用

 

System.Web.Abstractions;

System.Web.DynamicData;

System.Web.Mvc;

System.Web.Optimization;

System.Web.Razor;

System.Web.WebPages;

 

MVC有的文件夹:Controllers,Views , Models,Scripts,Content一个都不能少

 

 

 

2、配置Web.config文件

 

 

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

    <!--====MVC新增====-->
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>

  </configSections>

  <!--====MVC新增====-->
  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <!--====MVC新增====-->
  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        <add namespace="System.Web.Mvc.Html"/>
        <add namespace="System.Web.Routing"/>
        <add namespace="System.Linq"/>
        <add namespace="System.Collections.Generic"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>


  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebForm_Razor-20190326015656.mdf;Initial Catalog=aspnet-WebForm_Razor-20190326015656;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.2" />

    <!--====MVC新增(这里可以注释掉,不会报错)====-->
    <!--
    <assemblies>
      <add assembly="System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </assemblies>
    </compilation>-->

    <httpRuntime targetFramework="4.5.2" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
        <add namespace="Microsoft.AspNet.Identity" />

        <!--====MVC新增====-->
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        <add namespace="System.Web.Mvc.Html"/>
        <add namespace="System.Web.Routing"/>
        <add namespace="System.Linq"/>
        <add namespace="System.Collections.Generic"/>

      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
    <membership>
      <providers>
        <!--
          已在此模板中禁用 ASP.NET 成员身份。请访问以下链接 http://go.microsoft.com/fwlink/?LinkId=301889,以了解此模板中的 ASP.NET 成员身份支持
        -->
        <clear />
      </providers>
    </membership>
    <profile>
      <providers>
        <!--
          已在此模板中禁用 ASP.NET 成员身份配置文件。请访问以下链接 http://go.microsoft.com/fwlink/?LinkId=301889,以了解此模板中的 ASP.NET 成员身份支持
        -->
        <clear />
      </providers>
    </profile>
    <roleManager>
      <!--
            已在此模板中禁用 ASP.NET 成员身份角色。请访问以下链接 http://go.microsoft.com/fwlink/?LinkId=301889,以了解此模板中的 ASP.NET 成员身份支持
        -->
      <providers>
        <clear />
      </providers>
    </roleManager>
    <!--
            如果要部署到具有多个 Web 服务器实例的云环境,
            则应将会话状态模式从 "InProc" 更改为“自定义”。此外,
            还应将名为 "DefaultConnection" 的连接字符串更改为连接到
            SQL Server (包括 SQL Azure 和 SQL  Compact)实例,而不是连接到 SQL Server Express 实例。
      -->
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.webServer>
    <!--====MVC新增====-->
    <modules runAllManagedModulesForAllRequests="true">

      <remove name="FormsAuthentication" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

 

 

3、注册路由

 

            #region----====MVC新增====----
            RouteCollection routes = RouteTable.Routes;

            //避免对 Web 资源文件(例如 WebResource.axd 或 ScriptResource.axd)的请求传递给控制器  
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //避免aspx页面的请求传递给控制器
            routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");

            //路由注册
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
            #endregion

 

 

4、配置好了,开始写控制器和页面

 

 

 

5、排除报错原因

运行Index.cshtml发现报错:

 

 

搜索关键字:

找到该文件,把相关代码注释掉

 

6最后,运行成功!

 

 

 

 

 

posted on 2022-10-31 18:04  Jankie1122  阅读(78)  评论(0编辑  收藏  举报