简体   繁体   English

从AJAX和C#加载UI控件

[英]Loading UI Control From AJAX and C#

I am trying to dynamically load a PlaceHolder with a *.ascx page from a AJAX call. 我正在尝试通过AJAX调用以* .ascx页面动态加载PlaceHolder。 But am running into an issue with the static aspect. 但是在静态方面遇到了问题。

I cannot access the PlaceHolder as it's not a static member. 我不能访问PlaceHolder,因为它不是静态成员。 My code is as follows: 我的代码如下:

HTML: HTML:

    <div id="DInfo">
        <asp:PlaceHolder ID="PlaceHolderDInfo" runat="server"></asp:PlaceHolder>  
        <div id="response"></div>  
    </div>

C#: C#:

    [WebMethod]
    public static void SetD()
    {
       //SOME LOGIC TO FIND CORRECT ASCX PAGE
       ...

       //Load the control 
       PlaceHolderDInfo.Controls.Add(LoadControl([path to ascx]));
    }

AJAX: AJAX:

    $.ajax({
      type: "POST",
      url: "LivePlayer.aspx/SetD",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (response) {
        $("#response").html(response.d);
      },
      failure: function (response) {
         $("#response").html("error");
    }

The problem happens in the C# section as "PlaceHolderDInfo" throws the error: 由于“ PlaceHolderDInfo”引发错误,因此在C#部分中发生了问题:

  • " An object reference is required for the non-static field, method, or property ..." 非静态字段,方法或属性需要对象引用 。”

How can I reach the PlaceHolder from the SetD() method? 如何从SetD()方法访问PlaceHolder?

Thanks for any advice! 感谢您的任何建议!

Your code in the web method cannot use any object in your ASP.NET page. Web方法中的代码不能使用ASP.NET页中的任何对象。 Reason being: it's operating separately from the ASP.NET page process, therefore it knows nothing about viewstate, etc. You should treat it like any other web service. 原因是:它与ASP.NET页面进程分开运行,因此它对viewstate等一无所知。您应该像对待其他任何Web服务一样对待它。

That said, what needs to return is a string; 也就是说,需要返回的是一个字符串; please note, ASP.NET web forms and dynamic controls this way is not as easy as a framework like ASP.NET MVC, so you will have to overcome technical hurdles to get it to work. 请注意,这种方式的ASP.NET Web表单和动态控件不像ASP.NET MVC这样的框架那么简单,因此您必须克服技术上的障碍才能使其正常工作。 First being: any controls added by returning HTML as string and adding it to the DOM will not be retained in the postback lifecycle, and there will be issues with viewstate. 首先是:通过将HTML作为字符串返回并将其添加到DOM所添加的任何控件都不会保留在回发生命周期中,并且viewstate会出现问题。

It is possible to return a user control as a string; 可以将用户控件作为字符串返回; I've seen it setup as a handler, which streams back HTML as a string, but can't find the setup I've seen before. 我已经将它设置为处理程序,该处理程序将HTML作为字符串流回,但是找不到我之前见过的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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