[英]asp.net dropdownlist - C#.NET and javascript
我旁边有一个下拉菜单和一个div。 div中包含的文本应根据下拉菜单中选择的值进行更新。
我不想使用AutoPostBack功能。
使用下拉列表控件的OnChange客户端事件。 这是一个示例,该示例使用下拉列表的选定值更新div的内部文本:
<asp:DropDownList runat="server" ID="myDDL"
OnChange="document.getElementById('myDiv').innerText=this.value;">
</asp:DropDownList>
<div id="myDiv"></div>
正如人们所说的那样,如果不执行回发操作,则无法访问C#代码隐藏代码。
完成所需内容的一种方法是使用PageMethods。 这是完成此操作的Microsoft习惯用法,但是还有许多其他的Ajax库可以完成此操作。
在代码背后提供一个静态方法,该方法将从您的dropdownlist OnChange事件中调用。
[WebMethod]
public static string MyMethod()
{
// Your code goes here
return "The text for the div"
}
然后,从.aspx页调用此PageMethod:
您需要添加一个脚本管理器(在表单标签之后)
<asp:ScriptManager ID="scriptmanager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" ></asp:ScriptManager>
然后在OnChange事件(或从中调用的函数)中,您将:
<asp:DropDownList id="ddl" runat="server" OnChange="PageMethods.MyMethod(OnComplete);" />
其中OnComplete是用于处理PageMethod响应的javascript函数:
<script language="javascript">
function OnComplete(result, userContext, methodName) {
document.getElementById(yourDivId').innerText=result;
}
</script>
如果需要的话,您还可以使用parametrisated web方法:
[WebMethod]
public static string MyMethod(string myNeatParam)
{
// Your code goes here
return "The text for the div"
}
并调用:
PageMethods.MyMethod('SomeValue', OnComplete)
根据评论更新:
这是有关使用UpdatePanel执行所需操作的示例页面。 请记住,即使对用户透明,也会发生完整的回发。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UpdatePanelMadness._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ColorsDropDownList" runat="server" AutoPostBack="true"
onselectedindexchanged="ColorsDropDownList_SelectedIndexChanged">
<asp:ListItem Text="Red" Value="Red" />
<asp:ListItem Text="Green" Value="Green" />
<asp:ListItem Text="Blue" Value="Blue" />
</asp:DropDownList>
<div id="ColorDiv" runat="server">
<p>
Hello World!
</p>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
后面的代码:
namespace UpdatePanelMadness
{
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ColorsDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
ColorDiv.InnerText = this.ColorsDropDownList.SelectedValue;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.