在asp.net中,按钮可以有回发网址(即通过指定PostBackUrl - 我曾经使用它来截断过去的查询字符串参数 - 只需指定没有任何参数的页面网址)。使用按钮非常简单。
有谁知道这样做的最佳方法是使用下拉列表?如果我指定AutoPostBack(当选择更改时回发),似乎没有一种简单的方法来修改回发网址(即回发到没有查询字符串参数的页面)。
我猜测可能使用javascript进行自定义回发...但是有没有更好的方法 - 就像我缺少的asp.net按钮中的属性一样?
答案 0 :(得分:2)
没有DropDownList属性。您可以使用Response.Redirect
方法重定向用户,并使用Session collection
在请求之间保留数据。
答案 1 :(得分:1)
DropDownList没有该属性,但您可以通过一些技巧将此功能添加到您的网页中。首先让我描述为什么这个属性对你来说是必要的:
所以这是解决方案:
namespace myspace
{
public partial class EmployeePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//now you should get the correct url
//you can generate it right here but i prefer to use a special method to
//ensure that this url will be the same in all places of my code
string emptyEmpIdPostbackUrl = Utils.GetEmployeePageURL("");
//now call the main method
Utils.CreatePostbackUrl(this, "SetFilterUrl", emptyEmpIdPostbackUrl,
new List<WebControl> { ddlFilterCompany, ddlFilterDepartment, ddlFilterOwner,
ddlFilterType, ddlFilterDiscarded, ddlFilterChangeDate });
if (!IsPostBack)
{
...
}
}
...
}
public static class Utils
{
//page - your gridview page
//name - some custom name to ensure that different postbacks will work independently from each other
//url - the url with empty employee id
//controls - list of webcontrols for which you want to create postback url (i've got 6 dropdownlists on my own page)
public static void CreatePostbackUrl(Page page, string name, string url, List<WebControl> controls)
{
//create a hidden button with your postbackurl
Button btn = new Button();
btn.ID = name;
btn.PostBackUrl = url;
btn.Attributes.Add("style", "display: none;");
page.Form.Controls.Add(btn);
//register javascript that will simulate click on the hidden button
page.ClientScript.RegisterClientScriptBlock(page.GetType(), name + "Script",
"<script type=\"text/javascript\"> function " + name + "() {" +
"var btn = document.getElementById('" + btn.ClientID + "'); " +
"if (btn) btn.click();} </script>", false);
//and link this script to each dropdownlist in the list
foreach (WebControl ctrl in controls)
{
string attrName = "";
if (ctrl is DropDownList)
attrName = "onchange";
if (attrName != "")
ctrl.Attributes.Add(attrName, name + "()");
}
}
public static string GetEmployeePageURL(string empId)
{
return "emp.aspx" +
"?empid=" + empId;
}
}
}
在这些操作之后,您将获得带有隐藏按钮和一组web控件的页面,这些webcontrol将链接到此按钮并共享其PostBackUrl属性。
答案 2 :(得分:0)
如果您想直接POST到另一个页面,请使用隐藏按钮方法
<asp:DropDownList ID="lstMyDropDown" runat="server" ClientIDMode="Static" onchange="javascript:$get('btnHidden').click(); ">
<asp:ListItem Value="0" Text="Some Value 1" />
<asp:ListItem Value="1" Text="Some Value 2" />
</asp:DropDownList>
<asp:Button ID="btnHidden" runat="server" ClientIDMode="Static" PostBackUrl="~/myProcessingPage.aspx" OnClientClick="javascript:if($get('lstPrinterModel').selectedIndex < 1){return false;}" style="display:none" />