[英]get the ID of a selected value in the drop down list
我有一個具有Id_album屬性的專輯表。 以及具有Id_song屬性和Id_album作為外鍵屬性的歌曲表。 在aspx頁面中,我有一個下拉列表,其中包含要選擇的專輯名稱,以獲取其ID,並在歌曲表中使用該ID添加該專輯的新歌曲*取決於ID)到目前為止,我所做的一切對我來說都是Id_album從下拉列表中選擇專輯名稱時為1。 換句話說,所有歌曲均已添加到Id = 1專輯中。出了什么問題?
這是aspx頁面:
public partial class newSongs : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MusicStoreBL bl = new MusicStoreBL();
var data = bl.GetAlbums();
//GetAlbums is a function that returns the Id_album, AlbumName
albums.DataSource = data;
//albums is the HTML dropdownlist
albums.DataTextField = "AlbumName";
albums.DataValueField = "Id_Album";
albums.DataBind();
}
protected void save_Click(object sender, EventArgs e)
{
Song song = new Song();
//Song is a get/set model
song.Id_album = int.Parse(albums.SelectedValue);
song.SongName = songName.Text;
song.SongAuthor = author.Text;
song.MusicArtist = songArtist.Text;
song.Genre = genre.Text;
MusicStoreBL bl = new MusicStoreBL();
bl.CreateNewSong(song);
Response.Redirect("albumSelection.aspx");
}
}
您應該將數據綁定代碼放在以下if語句內的頁面加載事件處理程序中:
if(!Page.IsPostBack)
{
MusicStoreBL bl = new MusicStoreBL();
var data = bl.GetAlbums();
//GetAlbums is a function that returns the Id_album, AlbumName
albums.DataSource = data;
//albums is the HTML dropdownlist
albums.DataTextField = "AlbumName";
albums.DataValueField = "Id_Album";
albums.DataBind();
}
這樣,您只獲取一次數據,然后將它們綁定到相應的下拉列表控件。 否則,每次觸發回發時,例如從下拉列表控件中選擇一個元素或單擊一個按鈕等等, Page_Load
中的數據綁定代碼都會從頭開始運行。
那么,為什么總是獲得Id = 1?
您每次獲得的ID均為1的原因是,每次您單擊保存代碼都會在Page_Load
運行。 發生數據綁定,並且下拉列表的第一項是選中的項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.