Asp.Net sunucu tabanlı kod yazmak için kullanılan ortamdır. Client tarafında ise javascript ile kod geliştirebilirsiniz. Bu uygulamamızda Asp.Net sayfasında Listbox nesnesine eleman ekleme işlemini client taarfında gerçekleştireceğiz.
Yeni bir web sayfası oluşturalım. Aşağıdaki kodları tasarım kısmına yazalım. Öncelikle javascript tasarımını yapalım.
<asp:ListBox ID="ListBox1" runat="server" Width="150" Height="60"></asp:ListBox>
<br />
<hr />
<asp:TextBox ID="txtValue" runat="server" />
<asp:Button ID="btnAdd" Text="Add" runat="server" OnClientClick="return AddValues()" />
<script type="text/javascript">
function AddValues() {
var txtValue = document.getElementById("<%=txtValue.ClientID %>");
var listBox = document.getElementById("<%= ListBox1.ClientID%>");
var option = document.createElement("OPTION");
option.innerHTML = txtValue.value;
option.value = txtValue.value;
listBox.appendChild(option);
txtValue.value = "";
return false;
}
</script>
Şimdi aynı tasarımı jquery ile gerçekleştirelim.
<asp:ListBox ID="ListBox1" runat="server" Width="150" Height="60" SelectionMode = "Multiple"></asp:ListBox>
<br />
<hr />
<asp:TextBox ID="txtValue" runat="server" />
<asp:Button ID="btnAdd" Text="Add" runat="server" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=btnAdd]").bind("click", function () {
var value = $("[id*=txtValue]").val();
var listBox = $("[id*=ListBox1]");
var option = $("<option />").val(value).html(value);
listBox.append(option);
$("[id*=txtValue]").val("");
return false;
});
});
</script>
Web sayfasını çalıştıralım. Listbox nesnesine elemanlar eklenirken postback olmadan elemanların eklendiğini görürsünüz. Sunucu tarafında Listbox nesnesinin seçili elemanına aşağıdaki gibi ulaşabilirsiniz.
protected void Submit(object sender, EventArgs e)
{
string values = Request.Form[ListBox1.UniqueID];
}
|