Search code examples
javascriptjqueryasp.netajaxpagemethods

Error while trying to get asp.net(C#) textbox text from ajax static WebMethod


I am using an ajax htmleditor in asp.net web application so i am trying to get the text the user has entered in the editor then i will send that text back to the client javascript function that will show the text in a div. But I am getting this error "Object reference not set to an instance of an object."

Firstly i tried to access the text of textbox linked with htmleditorextender through javascript but it was not working for me so i moved to ajax webmethod but this time also i am facing a problem. Please Help me.

    [System.Web.Services.WebMethod]
    public static string seteditor()
    {
        String x="";
        try
        {
            Content c = new Content();
            x = c.txteditor.Text;
        }
        catch (Exception ex) { x=ex.Message; }
        return x;
    }

Here, txteditor is the ID of asp:textbox which is linked with ajaxcontroltoolkit htmleditorextender.


Solution

  • You cannot get your aspx controls inside a static method. If you are Calling a static method from jquery means the Page and its Controls don't even exist. You need to look another workaround for your problem.

    EDIT:

    I always pass my control values to page methods like this:

    Assume I have two text controls: txtGroupName and txtGroupLevel
    

    ...My JS with Jquery will be :

    var grpName = $("#<%=txtGroupName.ClientID%>").val();
    var grpLevel = $("#<%= txtGroupLevel.ClientID %>").val();
    
    data: "{'groupName':'" + grpName + "','groupLevel':'" +   grpLevel + "'}",
    

    Where groupName and groupRights are my webmethod parameters.

    EDIT2:

    Include your script like this:

    <script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery-1.4.1.js") %>"></script>  
    

    I suggest you to use the latest jquery version.