下拉列表的 PostBackUrl

发布于 2024-12-03 21:54:51 字数 276 浏览 0 评论 0原文

在 asp.net 中,按钮可以具有回发 url(即通过指定 PostBackUrl - 我过去曾使用它来截断查询字符串参数 - 只需指定不带任何参数的页面 url)。只需一个按钮,这非常简单。

有谁知道使用下拉列表执行此操作的最佳方法是什么?如果我指定 AutoPostBack(当选择更改时回发),似乎没有一种简单的方法来修改回发 url(即回发到没有查询字符串参数的页面)。

我猜也许用 javascript 进行自定义回发...但是有没有更好的方法 - 就像我缺少的 asp.net 按钮中的属性?

In asp.net, buttons can have postback urls (ie by specifying a PostBackUrl - I have used this to truncate querystring parameters in the past - by just specifying the page url without any parameters). This is super easy with a button.

Does anyone know what the best approach to doing this is with a dropdownlist? If I specify AutoPostBack (post back when the selection changes), there doesn't seem to be an easy way to modify the postback url (ie postback to the page without querystring parameters).

I'm guessing maybe doing a custom postback with javascript... but is there a better method - like a property as in the asp.net button that I am missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

红ご颜醉 2024-12-10 21:54:51

不,DropDownList 没有属性。您可以使用 Response.Redirect 方法重定向用户,并使用会话集合在请求之间保留数据。

No there isn't property with DropDownList. You can redirect the user using Response.Redirect method and use Session collection to persists data between requests.

别闹i 2024-12-10 21:54:51

DropDownList 没有该属性,但您可以采取一些技巧将此功能添加到您的页面中。首先,让我描述一下为什么您可能需要此属性的情况:

  1. 您有一个页面,其中包含从数据库填充的网格视图。例如,您公司的员工列表。这些字段包括 ID、姓名、姓氏、职位名称等。
  2. 您可以从项目的其他页面打开此页面,然后在某些情况下您必须在网格视图中选择一名员工。因此,您需要一个包含该员工 ID 的参数,您可以将其传递到 gridview 页面。
  3. 当然,出于此目的,您可以使用会话变量,但在某些情况下它们不被接受。例如,会话变量与后退按钮的配合不太好。您可以多次按返回,从浏览器历史记录中返回所选员工的 gridview 页面,但会话变量将包含最后设置的 id,而不是现在打开的 id!现在假设您有一个删除按钮,它通过会话 ID 来完成其工作。您会看到一个 gridview 行作为所选行,但删除了完全不同的行。
  4. 所以向其他页面传递参数的最好方式就是查询字符串。您可以轻松阅读并确保后退按钮不会破坏它们。
  5. 现在,当您在页面上并单击 gridview 行时,您必须修改 url 以便 url id 参数与所选行匹配。可以通过在每行中插入带有正确填充的 PostbackUrl 属性的链接按钮来完成。您单击该行中的链接按钮,该链接按钮包含具有正确行 id 的回发 URL,回发按照您的意愿进行,并且所选行和 url 都可以。
  6. 现在想象一下您处于更复杂的情况。您的页面上有一个下拉列表,它应该过滤网格视图中的员工列表。例如按部门。因此,您必须重新填充 gridview 并删除 url 中的 id,因为重新填充后,您不需要 gridview 具有任何选定的行。但你不能这样做,下拉列表没有这个神奇的属性......

所以这里是解决方案:

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;
        }

    }
}

在这些操作之后,你将获得带有隐藏按钮和一堆将链接到该按钮的网络控件的页面并共享其 PostBackUrl 属性。

There isn't that property for DropDownList but you can do some tricks to add this functionality to your pages. First of all let me describe a situation why this property may be necessary for you:

  1. You've got a page with a gridview filled from a database. For example a list of employees of your company. The fields are id, name, surname, jobname etc.
  2. You can open this page from other pages of your project and then in some cases you have to select one of your employees in the gridview. So you need a parameter with id of that employee that you can pass to the gridview page.
  3. Of course for this purposes you can use session variables but in some cases they are not accepted. For example session varibles aren't so good with the back button. You can press back many times, return to the gridview page from the browser history with selected employee but the session variable will contain the last set id and not the opened now! And now imagine that you have a delete button that do its job by the session id. You see one gridview row as the selected one but delete a completely different row.
  4. So the best way to pass parameters to other pages is the query string. You can read it with ease and be sure that the back button will not destroy them.
  5. Now when you are on the page and click the gridview rows you have to modify your url in order to the url id parameter matches the selected row. It can be done with linkbuttons inserted in each row with right filled PostbackUrl property. You click a linkbutton in the row, the linkbutton contains the postbackurl with the correct row id, the postback goes as you want to and both the selected row and the url are ok.
  6. And now imagine that you are in more complicated situation. You've got a dropdownlist on your page which should filter list of employees in your gridview. For example by departments. So you must refill the gridview and get rid of id in the url because after refill you don't need the gridview to have any selected rows. But you can't do it, the dropdownlist doesn't have this magic property...

So here is the solution:

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;
        }

    }
}

After these manipulations you'll get the page with a hidden button and bunch of webcontrols that will be linked to this button and share its PostBackUrl property.

浅忆流年 2024-12-10 21:54:51

如果您想直接发布到另一个页面,可以尝试隐藏按钮的方法

<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"  />

If you are wanting to POST directly to another page, use could try a hidden button approach

<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"  />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文