Ang*_*ris 0 javascript c# asp.net
我试图.aspx.cs调用testFun()从我的javascript代码调用的页面文件中的C#函数,我想传递2个值.我的javascript代码看起来有点像这样:
var questionsDone = 45;
var questionsCorrect = 23;
var exercisesDone = 65;
var exercisesCorrect = 12;
alert("<%= testFun() %>");
Run Code Online (Sandbox Code Playgroud)
我想要传递值的方法如下所示:
public string testFun(double questionScore, double exerciseScore){
return "done";
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是传递2个值,第一个是正值,(questionsCorrect/questionsDone)秒是正值(exercisesCorrect/exercisesDone).谁能帮我弄清楚怎么做?
有几种不同的方法可以做到这一点,但我喜欢用Ajax来调用"WebMethods"
您需要在主表单中包含一个脚本管理器,并将enablepagemethods设置为true
<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
Run Code Online (Sandbox Code Playgroud)
CS
[WebMethod]
public static string search()
{
return "worked";
}
Run Code Online (Sandbox Code Playgroud)
Javascript(JQuery Ajax.你可以使用你想要的任何lib)
$.ajax({
type: "POST",
url: "MyPage.aspx/search",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg)
}
});
Run Code Online (Sandbox Code Playgroud)
-编辑
要传递参数,您可以执行类似的操作并将其作为帖子正文发送.ASP.NET引擎会自动将其填充到您的方法参数中,假设您的javascript对象中的名称相同
var post = {
questionScore: 5,
exerciseScore: 5
}
$.ajax({
type: "POST",
url: "MyPage.aspx/testFun",
data: post,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg)
}
});
Run Code Online (Sandbox Code Playgroud)
CS
public static string testFun(double questionScore, double exerciseScore){ //both params should be 5
return "done";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |