如何在asp.net中发送jQuery变量值到服务器端

how can send a jQuery variable value to server side in asp.net

本文关键字:jQuery 变量值 服务器端 asp net      更新时间:2023-09-26

这是我的jQuery:

    $(document).ready(function () {
        var image = $('#man');
        var legTooltip = 'LEG';
        image.mapster({
            fillOpacity: 0.5,
            mapKey: 'alt',
            fillColor: "000000",
            listKey: 'alt',
            scaleMap: falsee,
            singleSelect: true,
            toolTipClose: ["tooltip-click", "area-click", "area-mouseout"],
            showToolTip: true,
            onClick: function (e) {
                if (e.key === 'leg') {
                   var **symp** = e.key;                        
                }                    
            },
            areas: [
            {
                key: "leg",
                toolTip: legTooltip
            }],
            render_highlight: {
                fade: false
            }                
        });
    });

现在我如何将变量symp的值发送到服务器端cs文件并将值保存到另一个服务器端变量?我对jquery和asp.net知之甚少。

如果我理解对了,你需要发送一个post请求到服务器。您可以通过使用jQuery方法post(这是一个简短的Ajax函数)来实现。

$.post( 
    "YourController/YourMethod", 
    { symp },
    function( response ) {
        //proccess the response here
    }
); 

在服务器端,在控制器中添加一个方法来获取

public class YourController : Controller
{
    //other methods and fields
    [HttpPost]
    public ActionResult YourMethod(<type of variable symp> symp)
    {
        //save this value wherever you want
        //return result of your request, so you can proccess it on the client side
        //e.g. that operation was successfully completed
    }
}

试试ajax:

$.(ajax){(
    url : 'url of the file in which yo want to process the data',
    method: 'post or get',
    data: {
        var1 : value1,
        var2 : value2    
        // these variables are available on the specified url  
        // use your variable(symp) here
    },
    success: function(response)
    {
         // response hold the server side response in it.
    }
)}

不要忘记在你的代码中包含jquery库

如果symp的值需要不断更新,那么Ajax会更好,正如Mayank Pandeys的回答。但是如果你只需要PostBack的值,一个HiddenField将是最简单的。

<asp:HiddenField ID="HiddenField1" runat="server" />
if (e.key === 'leg') {
    var **symp** = e.key;
    document.getElementById("<%= HiddenField1.ClientID %>").value = symp;
}

然后你可以在后面的代码中使用symp的值,通过从HiddenField获取值。

string symp = HiddenField1.Value;