简体   繁体   中英

asp.net add html elements from static method

I trying to add HTML or image button which can call code behind method, from a static method(Web method), I am calling web method through AJAX. My code is:

AJAX Method
function dispData()
    {

        var text_data = document.getElementById("TextBox1").value;
        var text_count = text_data.length;

        if (text_count >= 4)
        {
            alert("Text box val = " + text_data + " :Count = " + text_count);

            $.ajax({
                type: "POST",
                url: "WebForm2.aspx/ajaxData",
                data: JSON.stringify({ data: text_data }),
                contentType: 'application/json; charset=utf-8',
                dataType: "JSON",
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                },
                success: function (result) {
                    //alert("We returned: " + result.d);
                    $('#disp_ajax_data').html(result.d);<-- displaying result in div
                }
            })
            return false;//end of ajax

        }//end of if text_count.

    }//end of dispData.

[WebMethod(TransactionOption = TransactionOption.Supported)]
    public static string ajaxData(string data)
    {
       for (int loopCount = 0; loopCount < myCount; loopCount++)
            {
                string ele = oCompInfoSet[loopCount].Name + "<a href='codeBehindMethod()'>Add</a>" + "<br>";
                returnVal += ele;

            }//end for loop.
    }

I am displaying the names properly but not able to get the buttons. Can anyone please help

EDIT: From deostroll's help, my changed code, Oh... silly me.... I missed 'Static' keyword. I am trying to pass value now

for (int loopCount = 0; loopCount < oCompInfoSet.ComponentCount; loopCount++)
            {
                //Debug.WriteLine("In for loop");
                string ele_name = oCompInfoSet[loopCount].Component.Name;
                string ele = ele_name + "<a href='#' OnClick='add_ele("+ele_name+")'>Add</a> <br>";
                returnVal += ele;

            }//end for loop.

[WebMethod(TransactionOption = TransactionOption.Supported)]
    public static void addToStream()
    {
        Debug.WriteLine("Add to stream here");
    }//end of addToStream

JS METHOD:
function add_ele(name)
    {
        alert("add ele called, "+name);
        //PageMethods.addToStream();

    }//end of add_ele.

I am not getting alert also now, getting "Unidentified Error"....

Try looking at this: http://visualstudiomagazine.com/articles/2007/08/28/creating-and-consuming-aspnet-ajax-page-methods.aspx

The article above utilizes a concept called Page Methods. You have to enable it on the ScriptManager. Here is a simple example that is kind of in line with what you are doing:

Aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.PageMethods.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Page Methods</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"></asp:ScriptManager>
    <div> 
        <input type="button" onclick="GenerateLinks(5)" value="Add Links" />
        <div id="links"></div>
        <ul id="result">

        </ul>
    </div>
    </form>
    <script>
        /*
        *
        *   to generate guid
        *
        */
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                       .toString(16)
                       .substring(1);
        };

        function guid() {
            return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
                   s4() + '-' + s4() + s4() + s4();
        }

        function GetTime() {
            var g = guid();
            log('sent request for ' + g);
            PageMethods.GetTime(g, GetTimeSuccess);
        }

        function GetTimeSuccess(result) {
            log('result:' + result);
        }

        function GenerateLinks(n) {
            log('Generating links');
            PageMethods.GenerateLinks(n, function (result) {

                document.getElementById('links').innerHTML = result;
                log('added links');
            });
        }

        function log(msg) {
            var dt = new Date();
            var format = function(number){
                return number < 10 ? '0' + number : number
            };
            var h = format(dt.getHours());
            var m = format(dt.getMinutes());
            var s = format(dt.getMinutes());

            var ul = document.getElementById('result');
            var li = document.createElement('li');
            li.innerHTML = h + ':' + m + ':' + s + ' - ' + msg;
            ul.appendChild(li);
        }


    </script>
</body>
</html>

Code behind:

using System;
using System.Collections.Generic;
using System.Web.Services;

namespace WebApp.PageMethods
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string GenerateLinks(int number)
        {
            List<string> a = new List<string>();
            for (int i = 0; i < number; i++)
            {
                a.Add("<a href=\"javascript:GetTime()\">Get Time " + (i + 1) + "</a>");
            }

            return string.Join("<br/>", a);
        }

        [WebMethod]
        public static string GetTime(string guid)
        {
            return guid + " / " + DateTime.Now.ToLongTimeString();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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