调用C#方法从参数的JavaScript [英] Call c# method from javascript with parameter
问题描述
我要打电话与JavaScript参数一个C#方法。 %showDetail();如果我删除了该方法的参数s <这是可能的; %>
函数showDetail(库尔兹)
{
的String = kurz.toString();
<%showDetail(S); %取代;
}
这是我的C#的方法来测试:
公共无效showDetail(String s)将
{
Label_Test.Text = s.ToString();
}
公共无效showDetail()
{
Label_Test.Text =;
}
它工作正常,无参数,但与s变量,我得到一个编译器错误
CS0103:名称's'不在当前情况下存在
我与
<试过pre>
showDetail(一个Object){....}
并且还
showDetail(String s)将{....}
但它不能正常工作。
创建Web方法。这是从JavaScript调用C#方法简单而整洁的方式。您可以调用使用jQuery的Ajax这种方法。见一个WebMethod下面的例子。
[的WebMethod]
公共静态字符串RegisterUser(字符串s)
{
//做你的东西
返回stringResult;
}
,然后调用使用jQuery AJAX这种方法。您还可以传递参数。 ;像下面
函数showDetail(库尔兹){
字符串sParam = kurz.toString()给出
$阿贾克斯({
型:POST,
网址:PageName.aspx /方法名,
数据:{S:sParam},//传球参数
的contentType:应用/ JSON的;字符集= UTF-8,
数据类型:JSON,
成功:函数(retValue){
//做点什么返回值from.Net方法
}
});
}
I want to call a c# method with parameter from javascript. It is possible if I remove the parameter s of the method <% showDetail(); %>
function showDetail(kurz)
{
String s = kurz.toString();
<% showDetail(s); %>;
}
This is my c# methods to test:
public void showDetail(String s)
{
Label_Test.Text = s.ToString();
}
public void showDetail()
{
Label_Test.Text = "";
}
It works fine without parameter but with s variable I get a compiler error CS0103: The name 's' does not exist in the current context
I have tried it with
showDetail(Object s){....}
and also
showDetail(String s){....}
but It does not work.
Create a web method. That's an easy and neat way of calling c# methods from Javascript. You can call that method using jQuery Ajax. See the below example for a webMethod.
[WebMethod]
public static string RegisterUser(string s)
{
//do your stuff
return stringResult;
}
and then call this method using jQuery ajax. You can pass parameters also. like given below
function showDetail(kurz) {
String sParam = kurz.toString();
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{s:sParam}", // passing the parameter
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(retValue) {
// Do something with the return value from.Net method
}
});
}
这篇关于调用C#方法从参数的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!