开发者

What is the easiest way to call a C# method from Javascript

I have an LinkButton control which I need to add a c# method to. Currently when I use parse control and add the control to the page it changes the call to javascript and I get undefined. I figure a way around this would be to define a javascript function that would call the c# method from the code behind, but I cannot figure out how to do this.

Specfically when a linkbutton is clicked I need javascript to pass the ID of the linkbutton to a C# method.

I have tried this:

foreach (Control Control in myctrl.Controls)
           {
              if (Control is LinkButton)
                   {
                      LinkButton lb = (LinkButton)Control;
                      lb.Click += LinkButton_Click;

                    }
              Panel1.Controls.Add(myctrl);
           } 



public void LinkButton_Click(Object sender, EventArgs e)
        {
   BREAKPOIN开发者_运维知识库THERE>         Console.Write(e.ToString());

        }

It never fires when clicked. here is the code generated:

<a id="dnn_ctr954_ViewPromotions_LinkButton2" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;dnn$ctr954$ViewPromotions$LinkButton2&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, true))">Get your Free 2</a>

now if I put this in my aspx page, it works fine:

 <asp:LinkButton ID="test" OnClick="LinkButton_Click" runat="server">mybutton</asp:LinkButton>

I get this and it works fine:

<a id="dnn_ctr954_ViewPromotions_test" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;dnn$ctr954$ViewPromotions$test&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, true))">mybutton</a>


You can't do this per-se. Javascript exists on the client. C# code exists on the server. They can't possibly have any contextual knowledge of each other. Server code runs in response to an HTTP request.

That being said, you can create a web service method in C# and invoke it using javascript. Judging from the context of your question though, it may not do what you would like. Web service methods are static and don't have the same context as a regular postback.

However, you can check out a few articles like this one: Client-Side Web Service Calls with Ajax Extensions

Edit: With your edit, it sounds like you just want to make your button postback to the server. This is the core functionality of ASP.Net, and is easy to do. As other answers suggest, you just need to hook up a click event handler in your server code.


You could call a WebService or PageMethod from javascript written in C#.

Update: Since your using a LinkButton, you could simply define a click handler in your codebehind:

button.Click += button_Click


Example: load the page query from the back end via ajax NOTE Assumption is that jQuery is being used...just a sample

/************ the c# code ************************/

   [WebMethod]
    public static nameValue[] GetPageQueryList()
    {
        HttpRequest q = myRequest;
        NameValueCollection n = q.QueryString;
        List<nameValue> thisList = new List<nameValue>();

        if (n.HasKeys())
        {
            for (int i = 0; i < n.Count; i++)
            {
                nameValue newList = new nameValue(n.GetKey(i), n.Get(i));
                thisList.Add(newList);
            };
        }
        else
        {
            nameValue r = new nameValue("", "");
            thisList.Add(r);
        };
        return thisList.ToArray();
    }

#region nameValue
public class nameValue
{
    /// <summary>
    /// web service/webmethod needs 0 parameter constructor
    /// </summary>
    public nameValue()
    {
    }
    public nameValue(string name, string value)
    {
        Name = name;
        Value = value;
    }

    public string Name;
    public string Value;

}
#endregion

/******************************* the javascript code ***************/

// set the Query options from ajax results 

function testLoadQuery(jdata)
{
    var options = '';
    for (var i = 0; i < jdata.length; i++)
    {
        if (jdata[i].Name === "PID")
        {
            queryPatientID = jdata[i].Value;
        }
        options += '<option value="' + jdata[i].Name + '">' + '(' + jdata[i].Name + ')' + jdata[i].Value + '</option>';
    };
    $("select.requestSelect").html(options);
};
// read  on page load
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataFilter: function(data)
        {
            var msg;
            if (typeof (JSON) !== 'undefined' &&
    typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');
            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },
        url: "MyFancyPage.aspx/GetPageQueryList",
        success: function(msg)
        {
            testLoadQuery(msg);
            $("#testonlyRequest").text("Yeah QueryList did load");
        },
        failure: function(msg)
        {
            $("#testonlyRequest").text("oh darn QueryList did not load");
        }
    });

/********************** the html sample *******************/
    <div class="testonlyRequestContainer">
        <div class="testonly" id="testonlyRequest">
            testonlyRequest</div>
        <select class="testrequestSelect" id="testrequestSelect" title="request stuff">
        </select>
    </div>


You're looking for WebMethods, there's an example with jquery here, but can be adapted to basic javascript easily. The good sauce is on the "PageMethods.SomeMethod" part.


In my company's toolkit, we implemented a technology we call remote invoke. This consists of two parts - on the client side, there is a javascript method called RemoteInvoke() which takes a method name and an array of arguments to pass to the method. On the server side, you decorate a public method you would like to call with the attribute [RemoteInvokable]. RemoteInvoke matches signature as best as it can (type casting if needed) and then called the appropriate public method (if it found one).

It's not for things as simple as click actions, but it if you need more complicated things, it will work just great.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜