简体   繁体   English

将Javascript变量传递给C#函数aspx并从它返回到aspx页面

[英]Passing Javascript variable to C# function aspx and return from it to aspx page

How can I pass the variable to c# function?. 如何将变量传递给c#函数? Suppose that: 假设:

<script>

    var myValue;

    function setValue(idriga) {
        myValue = idriga;
    }

    function getValue() {
        return myValue;
    }

</script>

This is a script that set and get value. 这是一个设置和获取价值的脚本。 How can i pass the myValue value to ac# function code behind without calling aspx page and passing parameters but passing from aspx to aspx.cs and the from aspx.cs to aspx to show value returned from c# method (example search value into db and return other value?) 如何在不调用aspx页面和传递参数的情况下将myValue值传递给ac#函数代码,但是从aspx传递到myValue ,从myValue传递到aspx以显示从c#方法返回的值(示例搜索值到db和返回其他值?)

My function c# is: 我的函数c#是:

protected string SearchUserByGuid(Guid area) {
    return (from us in contextDB.AREAS
            where us.ID_AREAS == area
            select us.USER_NAME).Single();
}

I'm not sure I entirely understand what you are asking for, but if I do, it's not possible . 我不确定我完全理解你的要求,但如果我这样做,那是不可能的

What you can do is call a server-side method from JavaScript using AJAX. 可以做的是使用AJAX从JavaScript调用服务器端方法。 This server-side method can be a static [WebMethod] or a WebAPI method (if you use ASP.NET MVC or if you have a WebAPI Project). 此服务器端方法可以是静态[WebMethod]或WebAPI方法(如果您使用ASP.NET MVC或者如果您有WebAPI项目)。

For more about calling WebMethods with AJAX (and jQuery): http://deebujacob.blogspot.be/2012/01/aspnet-ajax-web-method-call-using.html 有关使用AJAX(和jQuery)调用WebMethods的更多信息: http//deebujacob.blogspot.be/2012/01/aspnet-ajax-web-method-call-using.html

For more about Web API: http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api 有关Web API的更多信息,请访问: http//www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

for passing variable to your WebMethod you can use ajax. 要将变量传递给WebMethod,您可以使用ajax。 With Jquery it it will be something like this 使用Jquery它会是这样的

$.ajax({
    type: "POST",
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    url: "YourPage.aspx/SearchUserByGuid",
    data:JSON.stringify({area: 'YourValueToPass'}),
    success: function (dt) { alert(dt);}, //all Ok
    error: function () { alert('error'); } // some error
});

also your WebMethod will be public static, so change your method declaration like this 您的WebMethod也将是公共静态的,因此请更改您的方法声明

[WebMethod]
public static string SearchUserByGuid(Guid area) {
    return (from us in contextDB.AREAS
        where us.ID_AREAS == area
        select us.USER_NAME).Single();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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