【问题标题】:Passing Javascript variable to C# function aspx and return from it to aspx page将 Javascript 变量传递给 C# 函数 aspx 并从它返回到 aspx 页面
【发布时间】:2013-12-29 13:23:56
【问题描述】:

如何将变量传递给 c# 函数? 假设:

<script>

    var myValue;

    function setValue(idriga) {
        myValue = idriga;
    }

    function getValue() {
        return myValue;
    }

</script>

这是一个设置和获取值的脚本。我如何将myValue 值传递给后面的 ac# 函数代码而不调用 aspx 页面并传递参数但从 aspx 传递到 aspx.cs 以及从 aspx.cs 到 aspx 以显示从 c# 方法返回的值(示例搜索值到db 并返回其他值?)

我的函数c#是:

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

【问题讨论】:

  • 您想在第一页加载时执行此操作吗?或动态
  • ehm 我认为是动态的.. 谢谢
  • 你尝试使用 HiddenField 吗?
  • @user1828965 所以使用webmethodGenericHandlers 等@Roy 说
  • Grundy 我之前使用过 [WebMethod] 方法。但是当我调用它时,我无法将变量传递给 c# 函数.....

标签: c# javascript asp.net


【解决方案1】:

为了将变量传递给您的 WebMethod,您可以使用 ajax。使用 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
});

您的 WebMethod 也将是公共静态的,因此请像这样更改您的方法声明

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

【讨论】:

  • json 值是多少?
  • {area: 'YourValueToPass'} - 对象的字段名称与您的 webmethod 中的参数名称相同,'YourValueToPass' - 您想要传递给 webmethod 的值
  • 好的。感谢您提供有用的答案!脾气暴躁!
【解决方案2】:

我不确定我是否完全理解您的要求,但如果我理解了,那不可能

可以做的是使用 AJAX 从 JavaScript 调用服务器端方法。此服务器端方法可以是静态 [WebMethod] 或 WebAPI 方法(如果您使用 ASP.NET MVC 或如果您有 WebAPI 项目)。

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

有关 Web API 的更多信息:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

【讨论】:

  • 我正在阅读文章!感谢您回答罗伊。当我确定这对我来说是一个有效的答案时,我会标记为答案。 Tjanks 又来了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2012-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多