通过另一个ASP控件发送ASP隐藏字段值

Sending ASP HiddenField Value through another ASP Control

本文关键字:ASP 隐藏 字段 控件 另一个      更新时间:2023-09-26

我有一个asp.net站点,其中我有两个文件需要彼此交谈。下面是我页脚的一段代码。ascx文件。我需要发送一个字符串到mobilead . asx .cs文件。下面是我从每个文件的相关代码。

我相信一切都设置正确,我只是不知道如何正确传递值。没有正确发送的值是SendA.value

下面是来自footer.ascx

的代码片段
<%@ Register TagPrefix="PSG" TagName="MobileAd" Src="~/MobileAd.ascx" %>
<asp:HiddenField runat="server" ID="SendA" value="" />
<script>
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) 
{
    document.getElementById('<%=SendA.ClientID%>').value = "mobile";
}   
else
{
    document.getElementById('<%=SendA.ClientID%>').value = "other";
}
</script>
<div class="bottom" align="center"> 
    <PSG:MobileAd ID="MobileAd" runat="server" AdType = <%=SendA.value%> />    
</div>

这是mobilead . asx .cs的接收端

private string _AdType;
public string AdType
{
    set
    {
        this._AdType = value;
    }
}
protected void Page_Load(object sender, EventArgs e)
{       
    string html = null;
    if (!string.IsNullOrEmpty(_AdType))
    {
        if (_AdType == "mobile")
        {
            html = "Mobile Ad Code";
        }
        else
        {
            html = "Tablet or Desktop Ad Code";
        }
        divHtml.InnerHtml = html;
    }

您正在使用javascript检测用户代理。但是,作为一个服务器控件,MobileAd.ascx在javascript执行之前被执行。您应该通过检查Request.UserAgentRequest.Browser.IsMobileDevice在服务器端执行此操作。如果属性AdType的唯一目的只是保存用户代理类型,您可以删除它并尝试像这样修改您的Page_Load方法:

protected void Page_Load(object sender, EventArgs e)
{       
    string html = null;
    if (Request.Browser.IsMobileDevice)
    {
        html = "Mobile Ad Code";
    }
    else
    {
        html = "Tablet or Desktop Ad Code";
    }
    divHtml.InnerHtml = html;    
}