我有一张图片和一个按钮。我有一种方法可以从一组图像中随机生成图像。出于某种原因,当我点击按钮时,除了执行事件外,它还会再次进入图像的“选择图像”方法并生成另一个 ID。
在这里可以找到图片的asp和图片Button;
<asp:Image ID="Image1" runat="server" Height="300px" Width="200px" OnDataBinding="chooseImage" />
<asp:ImageButton ID="aboutBtn" src="Resources/Icons/HomeAboutMeBtn.png" OnClick="AboutBtn_Click" runat="server" />
下面我还发布了按钮的事件处理程序,其中 childId 从“chooseImge”方法生成并存储在全局变量中。
protected void AboutBtn_Click(object sender, EventArgs e)
{
Response.Redirect("~/ChildDescription.aspx?id=" + childId);
}
有什么建议我为什么要这样做或如何做?基本上我想将显示在加载页面上的图像的 ID 作为 session 传递。
您可以在下面找到方法。基本上首先我从数据库中读取一组记录。然后我将 id 存储在数组中,然后通过调用随机生成器方法,它将从数组中随机选择一个 id。
protected void chooseImage(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(conString))
{
try
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("GetAllChildren", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
array.Add(reader["Child_ID"].ToString());
counter++;
}
connection.Close();
}
}
}
catch (Exception) { }
if (array.Count != 0)
{
try
{
using (SqlCommand command = new SqlCommand("GetChildDetails", connection))
{
command.CommandType = CommandType.StoredProcedure;
childId = Convert.ToInt32(array[RandomNumber(1, counter - 1)]);
command.Parameters.Add("@ChildID", SqlDbType.Int).Value = childId;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Image1.ImageUrl = "Resources/Children Images/" + reader["Primary_Image"].ToString();
ChildName.Text = reader["Child_Name"].ToString();
ChildName.Font.Size = 20;
surname.Text = reader["Child_Surname"].ToString();
surname.Font.Size = 20;
place.Text = reader["Location"].ToString();
place.Font.Size = 14;
genderLabel.Text = reader["Gender"].ToString();
genderLabel.Font.Size = 14;
DateTime birthday = DateTime.Parse(reader["Birthday"].ToString());
DateTime now = DateTime.Today;
int age = now.Year - birthday.Year;
if (birthday > now.AddYears(-age))
{
age--;
}
Years.Text = age.ToString() + "-years-old";
Years.Font.Size = 14;
}
connection.Close();
}
}
}
catch (Exception) { }
}
}
}
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
请您参考如下方法:
当您单击该按钮时,将首先触发 PostBack 操作,然后再单击。 如果 onload 方法中的代码可能只运行一次,那么您需要使用 Page.IsPostBack 将其包装起来,如下所示:
if (!Page.IsPostBack) {
chooseImage();
}
可以用Session保存childid的值
Session("id") = childId;
然后你可以使用:
protected void AboutBtn_Click(object sender, EventArgs e)
{
string id = (string) Session("id");
Response.Redirect("~/ChildDescription.aspx?id=" + id);
}
