ASP.NET在服务器端传递一个javascript值 [英] ASP.NET pass a javascript value in server side

查看:32
本文介绍了ASP.NET在服务器端传递一个javascript值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在服务器端(C#)中传递客户端(JS)值?

Hi how can I pass a client side (JS) value in server side (C#)?

例如

我有一个生成的表(上传图像后),它包含图像,我想选择图像并将ID扔回服务器端.

I have a generated table (after uploading images) and it contains images and I want to select the image and throw the ID back in server side.

我使用的uploade是JQuery Uploadify,并且具有"onComplete"功能

The uploade I used was JQuery Uploadify and I have a "onComplete" function


(simple code)
'onComplete': function (event, queueID, fileObj, response, data) {
    $('#imgs').append('<img id="' + queueID + '" src="' + response + '" alt="' + response + '" />');

我该怎么做?

推荐答案

要将javascript中的值发送到服务器,您有两个选择:

To send a value from javascript to the server you have a couple of options:

  1. 如果要保留在当前页面上,请使用AJAX
  2. 重定向到服务器端脚本并在查询字符串中传递值

让我们考虑第一种情况:

Let's consider the first case:

假设您有一个Web方法能够接收服务器上的值:

Assuming you have a web method capable of receiving the value on the server:

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" %>
<script type="text/C#" runat="server">
    // Server side script in the code behind that will receive
    // the value: The method needs to be static
    // and decorated with the WebMethod attribute
    [System.Web.Services.WebMethod]
    public static string Foo(string id)
    {
        return "ok";
    }
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            // Send an AJAX request to the server
            $.ajax({
                url: '/default.aspx/foo',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                // Pass the value as JSON string
                // You might need to include json2.js for the JSON.stringify
                // method: http://www.json.org/json2.js
                data: JSON.stringify({ id: 'someId123' }),
                success: function (result) {
                    // The result is also JSON
                    alert(result.d);
                }
            });
        });
    </script>
</head>
<body>
    <form id="Form1" runat="server">

    </form>
</body>
</html>

这篇关于ASP.NET在服务器端传递一个javascript值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆