Zunandi
Zunandi

Reputation: 164

PostBackUrl for a drop down list

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?

Upvotes: 2

Views: 2334

Answers (3)

euvikent
euvikent

Reputation: 11

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.

Upvotes: 1

Rory
Rory

Reputation: 1

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

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94643

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.

Upvotes: 2

Related Questions