如何在asp.net中将aspx.cs文件中的变量值设置为aspx文件?

时间:2014-01-25 17:10:14

标签: c# asp.net .net

我在Image.aspx.cs文件中编码为

public partial class Necklace : System.Web.UI.Page
{
    protected int PageId;
    protected void Page_Load(object sender, EventArgs e)
    {

        PageId = 12;
    }
}

我在Image.aspx文件中编码为

<div>
<asp:image ToolTip = "ASP Image Control" ID="Image1" runat="server" ImageUrl ="ImageCSharp.aspx?ImageID=<%= PageId %>" ></asp:image></div>

我在ImageCSharp.aspx.cs文件中编码为

protected void Page_Load(object sender, EventArgs e)
    {

        if (Request.QueryString["ImageID"] != null)
        {
            string strQuery = "select ImageName , ImageData from ImageTable where id=@id"; //,Category
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(Request.QueryString["ImageID"]);
            DataTable dt = GetData(cmd);
            if (dt != null)
            {
                Byte[] bytes = (Byte[])dt.Rows[0]["ImageData"];
                Response.Buffer = true;
                Response.Charset = "";
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                //Response.ContentType = dt.Rows[0]["Category"].ToString();
                Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["ImageName"].ToString());
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();
            }
        }
    }
    private DataTable GetData(SqlCommand cmd)
    {
        DataTable dt = new DataTable();
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            return dt;
        }
        catch
        {
            return null;
        }
        finally
        {
            con.Close();
            sda.Dispose();
            con.Dispose();
        }
    }
}

请帮我解释如何正确编码 ImageUrl =“ImageCSharp.aspx?ImageID = &lt;%= PageId%&gt; ... PageId应该是可变的。

1 个答案:

答案 0 :(得分:1)

只需将其设置在代码后面:

protected int PageId;

protected void Page_Load(object sender, EventArgs e)
{
   PageId = 12; // some value 
   Image1.ImageUrl ="ImageCSharp.aspx?ImageID=" + PageId;
}