使用带有处理程序的jquery加载usercontrol

时间:2013-02-08 09:22:10

标签: c# jquery asp.net webusercontrol dynamic-usercontrols

我想用jquery动态加载usercontrol。首先我在root网站上创建这个UserControl:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UcProduct.ascx.cs" Inherits="UC_UcProduct" %>
<p> Mohsen</p>

之后我创建.aspx页面并编写此代码以加载UserControl

<head runat="server">
    <title></title>

    <script src="Script/jquery-1.7.1.min.js"></script>
    <style>
        body {
            font-family: 'B Mitra', Tahoma, Arial;
            font-size: 20px;
            text-shadow: 4px 4px 4px #aaa;
        }
    </style>
    <script>
        $(function () {

            $("#UserCtrl").load("UcProduct.ascx");

        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="UserCtrl">
            111
        </div>
    </form>
</body>

此后我在App_code中创建了类

namespace Eshop
{

    public class jQueryHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { throw new NotImplementedException(); }
        }

        public void ProcessRequest(HttpContext context)
        {
            using (var dummyPage = new Page())
            {
                dummyPage.Controls.Add(GetControl(context));
                context.Server.Execute(dummyPage, context.Response.Output, true);
            }
        }
        private Control GetControl(HttpContext context)
        {
            // URL path given by load(fn) method on click of button
            string strPath = context.Request.Url.LocalPath;
            UserControl userctrl = null;
            using (var dummyPage = new Page())
            {
                userctrl = dummyPage.LoadControl(strPath) as UserControl;
            }
            // Loaded user control is returned
            return userctrl;
        }
    }
}

最后在web.config中添加此部分

<httpHandlers>
      <add verb="*" path="*.ascx" type="Eshop.jQueryHandler,App_Code" />
    </httpHandlers>

当运行Default.aspx页面时不加载userControl,当用firebug检查时我收到此消息 enter image description here 请帮我。谢谢大家。

1 个答案:

答案 0 :(得分:1)

我想这是文件扩展的问题。不允许服务器提供ascx文件。

您可以尝试:

<httpHandlers>
   <remove verb="*" path="*.ascx"/>
  <add verb="*" path="*.ascx" type="Eshop.jQueryHandler,App_Code" />
</httpHandlers>

声明path="*.myascx"的处理程序,然后在处理程序中加载相应的.ascx(这会改变你的ajax调用urls)