且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从一个html按钮的值调用一个c#方法

更新时间:2023-02-14 16:11:52

用于从html按钮调用服务器端功能,你需要这样调用。



你需要将该函数设置为static并使用webmethod属性进行标记。



然后在您的设计端编写javascript函数,该函数将触发ajax请求从您的代码后面调用该函数作为你使用jquery / javascript ajax请求从你身边调用任何webservice函数。



你的javascript函数看起来像这样。



< script type =text / javascript>

函数DeleteData(){


.ajax({

类型:POST,

url:Def ault.aspx / DeleteData,

数据:{},

contentType:application / json; charset = utf-8,

dataType:json,

成功:函数(msg){

alert(你的函数调用成功);

//如果你的Codebehind方法返回一些内容,那么将使用msg的.d属性访问该数据或结果

//像这样...


// alert(你的方法返回数据是......+ msg.d);

},

错误:function(msg){

alert(调用你的函数时出错了。);

}

} );

返回false;

}

< / script>





和你的代码背后的功能......







[WebMethod]

public static void DeleteData()

{

//你的代码

}

hi all,

i want to call a c# function from html buton's value without adding any javascript

<input type="button"  runat="server" id="test" name="test" value='<%=Resource.Language("_Description") %>' />


But its not calling my Language function which is on root folder on one of my Resource Class but if i am using the same text in asp label like this

<asp:Label ID="test" runat="server><%=Resource.Language("_Description") %>


this is calling my function and returns string, but the same thing is not being on button.

Waiting for your kind reply.
thanks

for calling server side function from html button you need to call like this.

you need to make that function static and mark that with webmethod attribute.

then write javascript function on your design side that will fire a ajax request to call that function from your code behind as you call any webservice function from your side using jquery/javascript ajax request.

Your javascript function look like this.

<script type="text/javascript">
function DeleteData() {


.ajax({
type: "POST",
url: "Default.aspx/DeleteData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("Your function called sucessfully");
//if your Codebehind method return something then that data or result will be accessed using .d attribute of msg
//like this...

//alert("Your method return data is ..." + msg.d);
},
error: function (msg) {
alert("There's some error in calling your function.");
}
});
return false;
}
</script>


and your code behind function like this...



[WebMethod]
public static void DeleteData()
{
//your code
}